Have a Read!

Hi Everyone.
The idea for this page is to provide new c users simple c tutorials to learn how to develop the logic and more importantly correct way to write syntax.
ENJOY !!!

Thursday, January 27, 2011

C PROGRAM FOR SUM OF N NUMBERS USING while,Do while & for Loop

I guess it is enough with the simple examples of if .So the examples below illustrate the use of while , do while and for loop all are doing the same thing. I have made the same code just to show the differences among these loops.I myself prefer for loop as it is summed up in just a single line.Anyways this is the code.
// WHILE LOOP

#include<stdio.h>
int main()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
    while (i<=n)
    {
      printf("%7d ",i); //%7 to print the digit within 7 slots
       sum = sum +i;
       i++;
    }
printf("\nSum = %d\n",sum);
return 0;
}

// DO WHILE LOOP
 
#include<stdio.h>
int main ()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
do
{
  printf("%7d,",i);
  sum=sum+i;
  i++;
  }
while(i<=n);
printf("\n\nSum=%d\n",sum);
return 0;
}

//FOR LOOP
 
#include<stdio.h>
int main()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
for(i=1;i<=n;i++)
    {
        printf("%7d",i);
        sum=sum+i;
    }
printf("\n\nSum = %d",sum);
return 0;
}

No comments:

Post a Comment

Related Posts with Thumbnails