In: Computer Science
Write a program that reads numbers from scanf1 (keyboard) and then sums them, stopping when 0 has been entered. Construct three versions of this program, using the while, do-while, and for loops.
Code using for loop:
#include<stdio.h>
int main()
{
int i,k=1,sum=0;
for(i=0;k!=0;i++)
{
printf("Enter your input: ");
scanf("%d",&k);
sum=sum+k;
}
printf("%d",sum);
}
Indentation:
Output;
Code using while loop:
#include<stdio.h>
int main()
{
int i,k=1,sum=0;
while(k)
{
printf("Enter your number:");
scanf("%d",&k);
sum=sum+k;
}
printf("Sum is : %d", sum);
}
Indentation:
Output:
Code using do-while loop:
#include<stdio.h>
int main()
{
int i,k,sum=0;
do
{
printf("Enter your number:");
scanf("%d",&k);
sum=sum+k;
}while(k);
printf("Sum is : %d", sum);
}
Indentation:
Output: