Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

LAB-3

3(a).Write a program to get sum of n natural numbers using while loop.

Source Code:

// This is a program to get sum of n natural numbers


#include<stdio.h>
void main()
{
int i=1,n,sum=0;
printf("Enter a number => ");
scanf("%d",&n);
while(i<=n)
{
sum=i+sum;
i++;
}
printf("Result:%d",sum);
}

Output:

3(b). Write a program to get sum of n natural numbers using do while loop.

Source Code:
// This is a program to get sum of n natural numbers
#include<stdio.h>
void main()
{
int i=1,a,sum=0;
printf("Enter Your Number => ");
scanf("%d",&a);
do {
sum=sum+i;
i++;
}
while(i<=a); printf("Result:%d",sum);
}

Output:

3(c). Write a program to get sum of n natural numbers using for loop.

Source Code:
// This is a program to get sum of n natural numbers
#include<stdio.h>
void main()
{
int i,sum=0,n;
printf("Enter a number => ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=i+sum;
}
printf("Result:%d",sum);
}

Output:

You might also like