Umar Farooq Umar Farooq - 2 months ago 10
C Question

How to use If statement as loop in C Programming?

I want to use If statement as loop, I am trying to write a program which should keep on getting input until user input 0, As user input 0, it should terminate and give sum of all entered numbers as output. For example:
Please enter value of N
1
4
5
0
Sum is=10

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n=0;
int sum;
printf("Enter Value of n");
scanf("%d",&n);

if(n!=0)
{
sum=sum+n;
}
else
printf("Sum is = %d", sum);

}


Program terminates after getting first input, ideally it should keep on getting input until 0 is entered. And then it should print sum of all entered values.

Answer

An if statement is not a loop and will never be a loop. Sounds like you want a while loop.

int main()
{
   int n=0;
   int sum = 0, counter;
   int aver;
   printf("Enter Value of n");
   scanf("%d",&n);

   while(n != 0)
   {
      sum=sum+n;
      printf("Enter Value of n");
      scanf("%d",&n);
   }
   printf("Sum is = %d", sum);
  }

This could be simplified even more using a "do while"

int main()
{
   int n=1;
   int sum = 0;

   do {
       printf("Enter Value of n");
       scanf("%d",&n);
       sum=sum+n;
   }
   while(n != 0)
   printf("Sum is = %d", sum);
  }