You are on page 1of 3

Five Useful C program examples

1 Finding sum of multiples

#include <stdio.h>
int main (){
int num, multiple3, multiple4;
multiple3=0;
multiple4=0;
for(num=3;num<=150;num++){
if (num % 4 ==0){
multiple4+=num;
}
else if (num % 3 == 0){
multiple3+=num;
}
}
printf("The sum of the multiples of 4 between 3 and 150 is %d\n",multiple4);
printf("The sum of the multiples of 3 between 3 and 150 is %d", multiple3);

2 counting characters

#include <stdio.h>

int main(){
char ch;
int number,num;
number =0; num =0;
printf ("Enter any statement\n");
while((ch=getchar())!='\n'){
number++;
if(ch==' '){num++;}
}
printf("The number of characters is %d\n",number);
printf("The number of spaces is %d",num);

3 Comparing number variables

#include <stdio.h>
int main (){
int a , b , c ,d ;
printf(" enter 4 numbers :");
scanf( "%d %d %d %d" , &a , &b , &c ,&d);
if (a > b){
printf (" a is greater than b");
}
else if (b > a){
printf ("\nb is greater than a");
}
if (a > c){
printf("\na is greater than c");
}
else{
printf("\nc is greater than a");
}
if (a > d) { printf ("\na is greater than d");
}
else { printf("\nd is greater than a");
}
return 0;

4 Comparing numbers using a function

#include <stdio.h>
int main(){
int x , sumofdiv(int);
printf("Enter a number: ");
scanf("%d",&x);
while(x!=0)
{
int sum = sumofdiv(x);
if(sum < x)
{
printf ("%d is deficient\n\n",x);
}
if(sum == x)
{
printf ("%d is perfect\n\n",x);
}
if (sum> x){printf("%d is abundant\n\n",x);
}
printf("The sum of the divisors is %d\n",sum);
printf("Enter a number: ");
scanf("%d",&x);
}
}
int sumofdiv(int q)
{
int sumdiv=0;
for(int h=1;h<q;h++)
{
if(q % h==0){
sumdiv+=h;}
}
return sumdiv;
}

5 Printing a pattern using nested for loop

#include <stdio.h>

int main(){
int a , b;
for(a=5;a>=1;a--)
{
for(b=5;b>=a;b--){

printf ("%d",b);

}
printf ("\n");

You might also like