Introduction

The main purpose of this blog is to share our experience with the world and get experience from the world. This will be a new venture for us and we are sure, we shall learn a lot with it. we will try to Explore our mind which will be very helpful for all us. As from its name, its a blog covering all the topics. we will try to post all the interesting topics and give our opinion. Do give your point of view in comments.


"NAVIGATE VIA BLOG ARCHIVE ON RIGHT TO GET WHAT YOU ARE LOOKING FOR"


Thursday, January 27, 2011

C CODE 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;
}

2 comments:

Related Posts with Thumbnails