In: Computer Science
Write a program that will calculate the sum of the first n odd integers, and the
sum of the first n even integers.
Use a Do while loop
Use a for loop
Here is a sample of how the program should run:
How many odd integers would you like to add? 5
Count Odd Integer Sum
1 1 1
2 3 4
3 5 9
4 7 16
5 9 25
The sum of the first 5 odd integers is 25
How many even integers would you like to add? 7
Count Even Integer Sum
1 2 2
2 4 6
3 6 12
4 8 20
5 10 30
6 12 42
7 14 56
The sum of the first 7 even integers is 56
Do you want to add again? Press y or n
y
How many odd integers would you like to add?
Make sure your program works with any input value from 1 to 1000.
REMEMBER! The sum of the first 5 odd integers is 1 + 3 + 5 + 7 + 9. It is NOT the
sum of the odd integers up to 5
Code:
#include<stdio.h>
int main(){
int i=1, sum=0, upto;
char again;
while(again!='n'){
printf("How many odd integers would
you like to add?");
scanf("%d",&upto);
int j=1;
printf("count odd integer
sum\n");
do {
sum=sum+i;
printf("%d %d
%d\n",j,i,sum);
j++;
i=i+2;
}while(j<=upto);
printf("The sum of the first %d odd
integers is %d\n",upto,sum);
printf("How many even integers
would you like to add?");
scanf("%d",&upto);
sum=0;
j=2;
printf("count even integer
sum\n");
for(i=1;i<=upto;i++){
j=i*2;
sum=sum+j;
printf("%d %d
%d\n",i,j,sum);
}
printf("The sum of the first %d
even integers is %d\n",upto,sum);
printf("Do you want to add again?
Press y or n\n");
scanf("%s",&again);
}
return 0;
}
Output:
Code with
explanation: