Saturday, July 23, 2011

A C program that find sum from 1 to 10

This is the program which uses the help of "For loop" to find the sum of the numbers from 1 to 10.

C Program:-



#include<stdio.h>

#include<conio.h>
void main(void)
{
clrscr();
int n,sum;
for(n=1;n<10;n++)
sum+=n;
printf("\n\nThe total from 1 to 10 is %d",sum);
getch();
}

Same Program in another Way:-

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int n,sum=0;
for(n=1;n<10;n++)
{
sum=sum+n;
printf("\n\ncount= %d  total= %d  ",n,sum);
}
printf("\n\nThe total from 1 to 10 is %d",sum);
getch();
}

Same program with setting the column width:-


#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int count=1,sum=0;
while(count<=10)
{
sum+=count;
printf("\n\n count=%2d    sum= %2d",count,sum);
count++;
}
getch();
}

Note:-
              In this program we set the column width by "%2d" this with set the column with two digit place.

No comments:

Post a Comment