Programs
Programs
C and C++
Program to find factors of a number using loops
1 * 15 = 15
3 * 5 = 15
5 * 3 = 15
15 * 1 = 15
1, 3, 5, 15 are the factors of 15.
#include <stdio.h>
int main()
{
int num;
printf(“\nEnter the number : “);
scanf(“%d”,&num);
int i,count = 0;
printf(“\nThe factors of %d are : “,num);
for(i = 1;i <= num; i++)
{
if(num % i == 0)
{
++count;
printf(“%d “,i);
}
}
printf(“\n\nTotal factors of %d : %d\n”,num,count);
}
1 C Program to Find Sum of n Natural Numbers For Loop
1.1 Algorithm
1.2 Program
2 C Program to Find the Sum of n Natural Numbers Using While Loop
2.1 Algorithm
2.2 Program
3 C Program to Find the Sum of n Natural Numbers Using Do While Loop
3.1 Program
3.2 Output
4 C Program to Find the Sum of n Natural Numbers Using Function
4.1 Algorithm
4.2 Program
5 C Program to Find the Sum of n Natural Numbers Using Recursion
5.1 Algorithm
5.2 Program
//C Program to Find the Sum of n Natural Numbers Using For
loop
#include<stdio.h>
int main()
{
//Declaring Variable
int n, i, sum = 0 ;
//Input Number
printf("Enter a Number\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum = sum + i;
}
printf("\nSum of %d Natural Numbers = %d",n, sum);
return 0;
}
//C Program to Find the Sum of n Natural Numbers Using While
Loop
#include<stdio.h>
void main()
{
int n, i=1, sum = 0 ;
printf("Enter a Number\n");
scanf("%d",&n);
while(i<=n)
{
sum = sum + i;
i++;
}
printf("\nSum of %d Natural Numbers = %d",n, sum);
}
//C Program to Find the Sum of n Natural Numbers Using Do
While Loop
#include<stdio.h>
int main()
{
int n, i=1, sum = 0 ;
printf("Enter A Number to Calculate Sum\n");
scanf("%d",&n);
do
{
sum = sum + i;
i++;
}while(i<=n);
return 0;
}
//C Program to Find the Sum of n Natural Numbers Using function
#include<stdio.h>
int sum(int);
void main()
{
int n, i=1, s;
printf("Enter A Number\n");
scanf("%d",&n);
s=sum(n);
printf("\nSum of %d Natural Numbers = %d",n, s);
}
int sum(int n)
{
int i,sum=0;
for(i=1;i<=n;i++)
{
sum = sum + i;
}
return (sum);
}
//C Program to Find the Sum of n Natural Numbers Using Recursion
#include<stdio.h>
int sum(int);
void main()
{
int n, s;
printf("Enter A Number\n");
scanf("%d",&n);
s=sum(n);
printf("\nSum of %d Natural Numbers = %d",n, s);
}
int sum(int n)
{
int s=0;
if(n==1)
return (n);
s = n + sum(n-1);
return (s);
}
1 C Program To Find Largest And Smallest Number In An Array Using Pointer