C 程序:打印奇数之和

如何用示例编写一个 C 程序来打印奇数之和?

C 程序:打印 1 到 n 之间的奇数之和

此程序允许用户输入最大限制值。接下来,此 c 程序计算 1 到最大限制值之间的奇数之和。

提示:我们在 C 程序:检查奇数或偶数 文章中解释了检查给定数字是偶数还是奇数的逻辑。

/* C Program to Print Sum of Odd Numbers from 1 to N */
 
#include<stdio.h>
 
int main()
{
  int i, number, Sum = 0;
 
  printf("\n Please Enter the Maximum Limit Value : ");
  scanf("%d", &number);
  
  printf("\n Odd Numbers between 0 and %d are : ", number);
  for(i = 1; i <= number; i++)
  {
  	if ( i%2 != 0 ) 
  	{
  		printf("%d  ", i);
        Sum = Sum + i;
  	}
  }
  printf("\n \n The Sum of Odd Numbers from 1 to %d  = %d", number, Sum);

  return 0;
}
C Program to Print Sum of Odd Numbers from 1 to N 1

在此“1 到 n 之间的奇数之和”示例程序中,For 循环将确保该数字在 1 和最大限制值之间。

for(i = 1; i <= number; i++)

在下一行,我们声明了If语句

if ( number % 2 != 0 )

任何不能被 2 整除的数字都是奇数。If 条件将检查数字除以 2 的余数是否不等于 0。如果条件为真,则该数字为奇数,并且 C 编程编译器将把 i 值添加到 sum 中。

C 程序:打印 1 到 n 之间的奇数之和

这个 C 语言查找奇数之和的程序与上面的程序相同,但我们修改了 for 循环以消除 If 语句

/* C Program to Print Sum of Odd Numbers from 1 to N */
 
#include<stdio.h>
 
int main()
{
  int i, number, Sum = 0;
 
  printf("\n Please Enter the Maximum Limit Value : ");
  scanf("%d", &number);
  
  printf("\n Odd Numbers between 0 and %d are : ", number);
  for(i = 1; i <= number; i=i+2)
  {
    Sum = Sum + i;
    printf("%d  ", i);
  }
  printf("\n \n The Sum of Odd Numbers from 1 to %d  = %d", number, Sum);

  return 0;
}

C 语言使用 for 循环计算奇数之和的输出

 Please Enter the Maximum Limit Value : 40

 Odd Numbers between 0 and 40 are : 1  3  5  7  9  11  13  15  17  19  21  23  25  27  29  31  33  35  37  39  
 
 The Sum of Odd Numbers from 1 to 40  = 400

程序:打印给定范围内的奇数之和

C 程序允许用户输入最小值和最大值限制。接下来,C 程序将计算最小值和最大值之间的奇数之和。

/* C Program to Print Sum of Odd Numbers in a Given Range */
 
#include<stdio.h>
 
int main()
{
  int i, Minimum, Maximum, Sum = 0;
 
  printf("\n Please Enter the Minimum, and Maximum Limit Values : \n");
  scanf("%d %d", &Minimum, &Maximum);
  
  printf("\n Odd Numbers between %d and %d are : \n", Minimum, Maximum);
  for(i = Minimum; i <= Maximum; i++)
  {
  	if ( i%2 != 0 )
	{
		printf("%d  ", i);
		Sum = Sum + i;
	}   
  }
  printf("\n \n The Sum of Odd Numbers betwen %d and %d  = %d", Minimum, Maximum, Sum);

  return 0;
}
 Please Enter the Minimum, and Maximum Limit Values : 
15
105

 Odd Numbers between 15 and 105 are : 
15  17  19  21  23  25  27  29  31  33  35  37  39  41  43  45  47  49  51  53  55  57  59  61  63  65  67  69  71  73  75  77  79  81  83  85  87  89  91  93  95  97  99  101  103  105  
 
 The Sum of Odd Numbers betwen 15 and 105  = 2760

评论已关闭。