Calculating sum of numbers from 1 to n
C Program
1.For Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,sum=0;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum = sum + i;
}
printf("Sum of numbers from 1 to %d is %d",n,sum);
}
2.While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,sum=0;
printf("Enter any number:");
scanf("%d",&n);
i =1;
while(i<=n)
{
sum = sum+i;
i++;
}
printf("sum of number from 1 to %d is %d",n,sum);
}
3.Do While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,sum=0;
printf("Enter any number:");
scanf("%d",&n);
i =1;
if(n!=0)
{
do
{
sum = sum+i;
i++;
}while(i<=n);
printf("sum of number from 1 to %d is %d",n,sum);
}
}
Java Program
1.For Loop
import java.util.Scanner;
public class SumTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
int sum=0;
for(int i=1;i<=n;i++)
{
sum = sum + i;
}
System.out.print("Sum of numbers from 1 to " + n + " is " + sum);
}
}
Java Program
2.While Loop
import java.util.Scanner;
public class SumTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
int sum=0,i=1;
while(i<=n)
{
sum = sum+i;
i++;
}
System.out.print("sum of number from 1 to" + n +" is "+sum);
}
}
Java Program
3. Do While Loop
import java.util.Scanner;
public class SumTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
int sum=0,i=1;
if(n!=0)
{
do
{
sum = sum+i;
i++;
}while(i<=n);
System.out.print("sum of number from 1 to " + n +" is "+sum);
}
}
}
0 Comments:
Post a Comment