Sie sind auf Seite 1von 39

swap two numbers without using a temporary

variable
#include <stdio.h>

int main()
{
int x = 10, y = 5;
// Code
x = x +
y = x x = x -

to swap 'x' and 'y'


y; // x now becomes 15
y; // y becomes 10
y; // x becomes 5

printf("After Swapping: x = %d, y = %d", x, y);


return 0;
}
write program to perform sum = 1+ (1+2) + (1+2+3) +.

int main(void)
{
int
n, sum;
printf("\nPlease enter a postive integer value");
scanf("%d", &n);
sum = n * ( n + 1 )/ 2;
printf("\n%d", sum);
return 0;
}

Write a c program to find largest among three numbers


using conditional operator
#include<stdio.h>
int main(){
int a,b,c,big;
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);

big=(a>b&&a>c?a:b>c?b:c);
printf("\nThe biggest number is: %d",big);
}

return 0;

include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,n3,small;
clrscr();
printf("Enter three numbers");
scanf("%d%d%d",&n1,&n2,&n3);
small=n1<n2?(n1<n3?n1:n3):(n2<n3?n2:n3);
printf("smallest number is:%d",small);
printf("press any key to close");
getch();
}

would like you to write a C Program to convert user


input of the temperature in Fahrenheit to Celcius,
include <stdio.h> //for printf and scanf
int main()
{
// Declare variables
double celsius, fahrenheit;
// Input
printf("Please enter a temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit); // Read input from user, store in
// fahrenheit

fflush(stdin); // Flush input buffer


// Calculation
celsius = (5.0/9.0) * (fahrenheit - 32); // We must use 5.0
// because we are playing with floating point
// numbers and don't want to do integer division.
// Output
printf("%4.1f degrees fahrenheit = %4.1f degrees
celsius\n", fahrenheit, celsius); // Variables are given from
left to right
getchar(); // For those icky windows compilers
return 0;
}

write a c program to calculate and display the


average of n numbers
#include<stdio.h>
#include<conio.h>
#define N 10
void main()
{
clrscr();

/* SYMBOLIC CONSTANT*/

int count;
float sum,average,number;
sum=0;
count=0;
while(count<N)
{
scanf("%f",&number);
sum=sum+number;
count=count+1;
}
average=sum/N;
printf("N=%d Sum=%f",N,sum);
printf(" Average=%f",average);
getch();
}

#include<stdio.h>

#include<conio.h>

void main()

int n,i,sum;

float av;

clrscr();

printf("\n Enter the value of N:");

scanf("%d",&n);

for(i =1;i<=n;i++)

sum= sum+i;

printf("\n sum is:%d",sum);

av=(float)sum/n;

printf("\n Average is: %f",av);

getche();

Write a program in C programming


language to print weekdays using switch
statement

#include<stdio.h> /* Header Files*/


#include<conio.h>
void main()
{
int a; /* variable declration */
clrscr();
printf("Enter Week day no = ");
scanf("%d",&a);
switch(a) /*test expression*/
{ case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thrusday");
break;
case 6:

printf("Friday");
break;
case 7:
printf("Staturday");
break;
default:
printf("Wrong Day NO Insert.");
}
getch();
}

write a program to determine whether the character entered is a capital letter, a


small case letter, a digit or a special symbol.

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\nEnter a character from the keyboard:");
scanf("%c",&ch);
if(ch>=97&&ch<=122)
printf("\nThe character is a lowercase letter");
if(ch>=48&&ch<=57)

printf("\nThe character is a digit");


if((ch>=0&&ch<48)||(ch>57&&ch<65)||(ch>=90&&ch<97)||(ch>122))
printf("\nThe character is a special symbol");
printf("\n press any key to exit.");
getch();
}

Write a C program to converting


uppercase to lowercase.
#include <stdio.h>
#include<conio.h>
void main()
{
char letter = 0;
printf("Enter an uppercase letter: It);
scanf("%c", &letter);
if(letter >= 'A')
if (letter <= 'Z')
{
letter = letter - 'A'+ 'a';
printf("An uppercase %c\n", letter);
}
else
printf("A capital letter please.\n");
getch();
}
OUTPUT:
Enter an uppercase letter:
S
An uppercase s

Write a c program to reverse a given number

#include<stdio.h>
int main(){
int num,r,reverse=0;
printf("Enter any number: ");
scanf("%d",&num);
while(num){
r=num%10;
reverse=reverse*10+r;
num=num/10;
}
printf("Reversed of number: %d",reverse);
return 0;
}
Sample output:
Enter any number: 12
Reversed of number: 21

#include <stdio.h>
#include <conio.h>
#include<math.h>
void main()
{
long n,j;
clrscr();
printf("Enter the No :- ");
scanf("%ld",&n);
printf("\n");
printf("Reverce of the number is....");
while(n>0)
{
j = n%10;
printf("%ld",j);
n /= 10;
}
getch();
}
/*
********

OUTPUT
********
Enter the No :- 23456
Reverce of the number is....65432
*/

C Program to Count the Number of Vowels


& Consonants in a Sentence
1. /*
2. * C program to read a sentence and count the total number of vowels
3. * and consonants in the sentence.
4. */
5. #include <stdio.h>
6.
7. void main()
8. {
9.
char sentence[80];
10.
int i, vowels = 0, consonants = 0, special = 0;
11.
12.
printf("Enter a sentence \n");
13.
gets(sentence);
14.
for (i = 0; sentence[i] != '\0'; i++)
15.
{
16.
if ((sentence[i] == 'a' || sentence[i] == 'e' || sentence[i]
==
17.
'i' || sentence[i] == 'o' || sentence[i] == 'u') ||
18.
(sentence[i] == 'A' || sentence[i] == 'E' || sentence[i] ==
19.
'I' || sentence[i] == 'O' || sentence[i] == 'U'))
20.
{
21.
vowels = vowels + 1;
22.
}
23.
else
24.
{
25.
consonants = consonants + 1;
26.
}
27.
if (sentence[i] =='t' ||sentence[i] =='\0' || sentence[i] =='
')
28.
{
29.
special = special + 1;
30.
}
31.
}
32.
consonants = consonants - special;
33.
printf("No. of vowels in %s = %d\n", sentence, vowels);
34.
printf("No. of consonants in %s = %d\n", sentence, consonants);
35. }

Check Whether a Character is Vowel or consonant


#include <stdio.h>
int main(){
char c;
printf("Enter an alphabet: ");

scanf("%c",&c);
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||
c=='U')
printf("%c is a vowel.",c);
else
printf("%c is a consonant.",c);
return 0;
}

Write a C Program to Find the Roots of a Quadratic


Equation by using if-else and else-if Statement
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float A , B , C , root1 , root2;
float realp , imgp , disc;
/* realp stands for Real Part and imgp stands for Imaginary Part */
clrscr();
printf(" Enter the values of A , B and C\n");
scanf("%f%f%f" , &A , &B , &C);
if(A==0 || B==0 || C==0)
{
printf(" Error: Roots cannot be determined\n");
}
else
{
dis = (B * B) - (4 * A * C);
if(disc<0)
{
printf(" Imaginary Roots\n");
realp = -B/(2*A);
imagp = sqrt(abs(disc))/(2*A);
printf(" Root1 = %f + i%f\n" , realp , imagp);
printf(" Root2 = %f - i%f\n" , realp , imagp);
}
else if( disc == 0)
{
printf(" Roots are real and equal\n");
root1 = -B/(2 * A);
root2 = Root1;
printf(" Root1 = %f\n" , root1);

printf(" Root2 =%f\n" , root2);


}
else if(disc>0)
{
printf(" Roots are real and distinct\n");
root1 = (-B + sqrt(disc))/(2*A);
root2 = (-B - sqrt(disc))/(2*A);
printf(" Root1 = %f\n" , root1);
printf(" Root2 = %f\n" , root2);
}
}
}

/* End of main() */

# include <stdio.h>
# include <conio.h>
# include <math.h>
void main()
{
float a, b, c, d, real, imag, root1, root2, n ;
int k ;
printf("\n Enter the values of A : ") ;
scanf("%f", &a) ;
printf("\n Enter the values of B : ") ;
scanf("%f", &b) ;
printf("\n Enter the values of C : ") ;
scanf("%f", &c) ;
if(a != 0){
d = b * b - 4 * a * c ;
if(d < 0)
k = 1 ;
if(d == 0)
k = 2 ;
if(d > 0)
k = 3;
switch(k){
case 1 :
printf("\n RESULT
printf(" Roots of
printf("\n Root-1
printf("\n Root-2
break ;

: \n Roots are complex/imaginary number.\n");


quadratic equation are: ");
= %.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));
= %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

case 2 :
printf("\n RESULT : \n Both roots are real numbers and equal.\n");
root1 = -b /(2* a);
printf(" Root of quadratic equation is:\n Root-1 = Root-2 = %.3f
",root1);

break ;

case 3 :
printf("\n RESULT : \n Roots are real numbers and unequal.\n");
root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a);
printf(" Roots of quadratic equation are:\n Root-1 = %.3f , Root-2
= %.3f",root1,root2);
break ;
}
}
else
printf("\n RESULT :\n Equation is linear.") ;
getch() ;
}

Write a C program to find the factorial of a number, where the number is entered by
user. (Hints: factorial of n = 1*2*3*...*n
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){
/* while loop continues util test condition number>0 is
true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}

Source Code to Make Simple Calculator in C


programming
/* Source code to create a simple calculator for addition, subtraction, multiplication
and division using switch...case statement in C programming. */
# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {

case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;

}
return 0;

C Program to Display Character from A to


Z Using Loop
/* C program to display character from A to Z using loops. */
#include <stdio.h>
int main()
{
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
return 0;
}
/* C program to display character from A to Z using loops either in uppercase or
lowercase depending upon the data from user */
#include <stdio.h>
int main()
{
char c;
printf("Enter u to display characters in uppercase and l to display in lowercase:
");
scanf("%c",&c);
if(c=='U' || c=='u')
{
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
}
if (c=='L' || c=='l')
{
for(c='a'; c<='z'; ++c)
printf("%c ",c);
}
if (c!='U' || c!='L' || c=='u' || c=='l')

printf("Error !!!");
return 0;

C Program to Find GCD of two Numbers


/* C Program to Find Highest Common Factor. */
#include <stdio.h>
int main()
{
int num1, num2, i, hcf;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i<=num1 || i<=num2; ++i)
{
if(num1%i==0 && num2%i==0) /* Checking whether i is a factor of both
number */
hcf=i;
}
printf("H.C.F of %d and %d is %d", num1, num2, hcf);
return 0;
}

In this program, two integers are taken from user and stored in variable num1 and num2.
Then i is initialized to 1 and for loop is executed until i becomes equal to smallest of two
numbers. In each looping iteration, it is checked whether i is factor of both numbers or not.
If i is factor of both numbers, it is stored to hcf. When for loop is completed, the H.C.F of
those two numbers will be stored in variable hcf.

2. Source Code to Find HCF or GCD


#include <stdio.h>
int main()
{
int num1, num2, min,i;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
min=(num1>num2)?num2:num1; /* minimum value is stored in variable min */
for(i=min;i>=1;--i)
{
if(num1%i==0 && num2%i==0)
{
printf("HCF of %d and %d is %d", num1, num2,i);
break;
}
}
return 0;
}

This program is little optimized than the program above to find H.C.F. In this program,
smallest of two integers entered by user is stored in variable min. Then i is initialized
to min and for loop is executed. In each looping iteration, whether i is factor of these two
numbers is checked. If i is a factor of these two numbers then, i will be the highest common
divisor and loop is terminated usingbreak statemen

3. Source Code to Find HCF or GCD


#include<stdio.h>
int main()
{
int num1,num2;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
printf("HCF of %d and %d is ",num1 , num2);
while(num1!=num2)
{
if(num1>num2)
num1-=num2;
else
num2-=num1;
}
printf("%d",num1);
return 0;
}

This is the best way to find HCF of two numbers. In this method, smaller number is
subtracted from larger number and that number is stored in place of larger number. This
process is continued until, two numbers become equal which will be HCF.

C Program to Find LCM of two Numbers


/* C program to find LCM of two positive integers entered by user */
#include <stdio.h>
int main()
{
int num1, num2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
max=(num1>num2) ? num1 : num2; /* maximum value is stored in variable max
*/
while(1)
/* Always true. */
{
if(max%num1==0 && max%num2==0)
{
printf("LCM of %d and %d is %d", num1, num2,max);

break;
}
++max;

/* while loop terminates. */

}
return 0;
}

In this program, user is asked to enter two positive integers which will be stored in
variable num1 andnum2 respectively and largest of two integers is assigned to
variable max. Then, while loop is executed and in each iteration it is checked
whether max is perfectly divisible by two numbers entered by user or not. If max is not
perfecly divisible, max is increased by 1 and this process goes not until max is perfectly
divisible by both numbers. The test condition of while loop in above program is always true
so, the loop is terminated using break statement .
#include<stdio.h>
int main()
{
int n1,n2,temp1,temp2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
temp1=n1;
temp2=n2;
while(temp1!=temp2)
{
if(temp1>temp2)
temp1-=temp2;
else
temp2-=temp1;
}
printf("LCM of two numbers %d and %d is %d", n1, n2, (n1*n2)/temp1);
return 0;
}

C Program to Find Number of Digits in a Number


#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10;
/* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}

Output
Enter an integer: 34523
Number of digits: 5
This program takes an integer from user and stores that number in variable n. Suppose,
user entered 34523. Then, while loop is executed because n!=0 will be true in first
iteration. The codes inside while loop will be executed. After first iteration, value of n will be
3452 and count will be 1. Similarly, in second iteration n will be equal to 345 and count will
be equal to 2. This process goes on and after fourth iteration, n will be equal to 3
and count will be equal to 4. Then, in next iteration n will be equal to 0 and count will be
equal to 5 and program will be terminated as n!=0 becomes false.

Source Code to Calculate Power


/* C program to calculate the power of an integer*/
#include <stdio.h>
int main()
{
int base, exp;
long long int value=1;
printf("Enter base number and exponent respectively: ");
scanf("%d%d", &base, &exp);
while (exp!=0)
{
value*=base; /* value = value*base; */
--exp;
}
printf("Answer = %d", value);
}

Output
Enter base number and exponent respectively: 3
4
Answer = 81
This program takes base number and exponent from user and stores in
variable base and exprespectively. Let us suppose, user entered 3 and 4 respectively.
Then, while loop is executed with test condition exp!=0 . This test condition will be true
and value becomes 3 after first iteration and value of exp will be decreased to 3. This
process goes on and after fourth iteration, value will be equal to 81(3*3*3*3) and exp will

be equal to 0 and while loop will be terminated. Here, we have declared variable value of
type long long int because power of a number can be very large.

Source code to calculate power using recursion


/* Source Code to calculate power using recursive function */
#include <stdio.h>
int power(int n1,int n2);
int main()
{
int base, exp;
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number(positive integer): ");
scanf("%d",&exp);
printf("%d^%d = %d", base, exp, power(base, exp));
return 0;
}
int power(int base,int exp)
{
if ( exp!=1 )
return (base*power(base,exp-1));
}

Source Code to Calculate Sum of Natural Numbers


/* This program is solved using while loop. */
#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
count=1;
while(count<=n)
/* while loop terminates if count>n */
{
sum+=count;
/* sum=sum+count */
++count;
}
printf("Sum = %d",sum);
return 0;
}

Source Code to Calculate Sum Using for Loop


/* This program is solve using for loop. */

#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
sum+=count;
/* sum=sum+count */
}
printf("Sum = %d",sum);
return 0;
}

Output
Enter an integer: 100
Sum = 5050
Both program above does exactly the same thing. Initially, the value of count is set to 1.
Both program have test condition to perform looping iteration until
condition count<=n becomes false and in each iteration ++count is executed.
This program works perfectly for positive number but, if user enters negative number or
0, Sum = 0 is displayed but, it is better is display the error message in this case. The above
program can be made user-friendly by adding if else statement as:
/* This program displays error message when user enters negative number or 0 and
displays the sum of natural numbers if user enters positive number. */
#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
if ( n<= 0)
printf("Error!!!!");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
sum+=count;
/* sum=sum+count */
}
printf("Sum = %d",sum);
}
return 0;
}

Source Code to Calculate Standard Deviation by


Passing it to Function
/* Source code to calculate standard deviation. */
#include <stdio.h>
#include <math.h>
float standard_deviation(float data[], int n);
int main()
{
int n, i;
float data[100];
printf("Enter number of datas( should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0; i<n; ++i)
scanf("%f",&data[i]);
printf("\n");
printf("Standard Deviation = %.2f", standard_deviation(data,n));
return 0;
}
float standard_deviation(float data[], int n)
{
float mean=0.0, sum_deviation=0.0;
int i;
for(i=0; i<n;++i)
{
mean+=data[i];
}
mean=mean/n;
for(i=0; i<n;++i)
sum_deviation+=(data[i]-mean)*(data[i]-mean);
return sqrt(sum_deviation/n);
}

C Program to Find Size of int, float,


double and char of Your System
/* This program computes the size of variable using sizeof operator.*/
#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int: %d bytes\n",sizeof(a));
printf("Size of float: %d bytes\n",sizeof(b));
printf("Size of double: %d bytes\n",sizeof(c));
printf("Size of char: %d byte\n",sizeof(d));

return 0;
}

C Program to Find Largest Number Using


Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main(){
int i,n;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
data=(float*)calloc(n,sizeof(float)); /* Allocates the memory for 'n' elements */
if(data==NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
printf("\n");
for(i=0;i<n;++i) /* Stores number entered by user. */
{
printf("Enter Number %d: ",i+1);
scanf("%f",data+i);
}
for(i=1;i<n;++i) /* Loop to store largest number at address data */
{
if(*data<*(data+i)) /* Change < to > if you want to find smallest number */
*data=*(data+i);
}
printf("Largest element = %.2f",*data);
return 0;
}

C Program to Find G.C.D Using


Recursion
/* Example to calculate GCD or HCF using recursive function. */
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return 0;
}

int hcf(int n1, int n2)


{
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
}

C program to Calculate Factorial of a


Number Using Recursion
/* Source code to find factorial of a number. */
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}

C Program to Check Prime or Armstrong Number Using User-defined Function


/* C program to check either prime number or Armstrong number depending upon
the data entered by user. */
#include <stdio.h>
int prime(int n);
int armstrong(int n);
int main()
{
char c;
int n,temp=0;
printf("Eneter a positive integer: ");
scanf("%d",&n);
printf("Enter P to check prime and A to check Armstrong number: ");
c=getche();
if (c=='p' || c=='P')
{
temp=prime(n);
if(temp==1)
printf("\n%d is a prime number.", n);
else
printf("\n%d is not a prime number.", n);

}
if (c=='a' || c=='A')
{
temp=armstrong(n);
if(temp==1)
printf("\n%d is an Armstrong number.", n);
else
printf("\n%d is not an Armstrong number.",n);
}
return 0;

}
int prime(int n)
{
int i, flag=1;
for(i=2; i<=n/2; ++i)
{
if(n%i==0)
{
flag=0;
break;
}
}
return flag;
}
int armstrong(int n)
{
int num=0, temp, flag=0;
temp=n;
while(n!=0)
{
num+=(n%10)*(n%10)*(n%10);
n/=10;
}
if (num==temp)
flag=1;
return flag;
}

C Program to Display Prime Numbers


Between Intervals Using User-defined
Function
#include<stdio.h>
int check_prime(int num);
int main(){
int n1,n2,i,flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d",&n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1;i<n2;++i)
{

flag=check_prime(i);
if(flag==0)
printf("%d ",i);
}
return 0;
}
int check_prime(int num) /* User-defined function to check prime number*/
{
int j,flag=0;
for(j=2;j<=num/2;++j){
if(num%j==0){
flag=1;
break;
}
}
return flag;
}

C Programming Code To Create Pyramid


and Pattern
C Program To display the triangle using *, numbers and
character
Write a C Program to print half pyramid as using * as shown in figure
below.
*
* *
* * *
* * * *
* * * **
#include <stdio.h>
int main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
printf("* ");

}
printf("\n");

}
return 0;

Write a C Program to print half pyramid as using numbers as shown in


figure below.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h>
int main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

Write a C Program to print triangle of characters as below


A
BB
C CC
D D D D
E EE E E

#include<stdio.h>
int main()
{
int i,j;
char input,temp='A';
printf("Enter uppercase character you want in triangle at last row: " );
scanf("%c",&input);
for(i=1;i<=(input-'A'+1);++i)
{
for(j=1;j<=i;++j)
printf("%c",temp);
++temp;
printf("\n");
}
return 0;
}

C Program To Display inverted half pyramid using * and


numbers
Write a C Program to print inverted half pyramid using * as shown below.
* * * **
* * * *
* * *
* *
*
#include <stdio.h>
int main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(j=1;j<=i;++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

1 2 3 4 5

1 2 3 4
1 2 3
1 2
1
Write a C Program to print inverted half pyramid as using numbers as
shown below.
#include <stdio.h>
int main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(j=1;j<=i;++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

C Program To display the pyramid of * and digits


Write a C program to print pyramid using *.

*
* * *
* * * * *
* ** * * * *
* * * ** * * * *

#include <stdio.h>
int main()
{
int i,space,rows,k=0;

printf("Enter the number of rows: ");


scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(space=1;space<=rows-i;++space)
{
printf(" ");
}
while(k!=2*i-1)
{
printf("* ");
++k;
}
k=0;
printf("\n");
}
return 0;
}

Write a C program to print the pyramid of digits in pattern as below.


1
2 3 2
3 4 5 43
4 5 6 7 654
5 6 7 8 987 65

#include <stdio.h>
int main()
{
int i,space,rows,k=0,count=0,count1=0;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(space=1;space<=rows-i;++space)
{
printf(" ");
++count;
}
while(k!=2*i-1)
{
if (count<=rows-1)
{
printf("%d ",(i+k));
++count;
}

else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;

}
count1=count=k=0;
printf("\n");
}
return 0;
}

Write a C program to display reverse pyramid.


* * * ** * * * *
* ** * * * *
* * * * *
* * *
*

#include<stdio.h>
int main()
{
int rows,i,j,space;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(space=0;space<rows-i;++space)
printf(" ");
for(j=i;j<=2*i-1;++j)
printf("* ");
for(j=0;j<i-1;++j)
printf("* ");
printf("\n");
}
return 0;
}

C Program to Draw Pascal's triangle

1
1
1
1

1
2

1 4
1 5

1
3

6
10

1
4

10 5

#include<stdio.h>
int main()
{
int rows,coef=1,space,i,j;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=0;i<rows;i++)
{
for(space=1;space<=rows-i;space++)
printf(" ");
for(j=0;j<=i;j++)
{
if (j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
printf("%4d",coef);
}
printf("\n");
}
}

C Program to display Floyd's Triangle.


1
2 3
4 5 6
7 8 9 10
#include<stdio.h>
int main()
{
int rows,i,j,k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);

for(i=1;i<=rows;i++)
{
for(j=1;j<=i;++j)
printf("%d ",k+j);
++k;
printf("\n");
}
}

Source code to display Fibonacci series up to n


terms
/* Displaying Fibonacci sequence up to nth term where n is entered by user. */
#include <stdio.h>
int main()
{
int count, n, t1=0, t2=1, display=0;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count<n)
{
display=t1+t2;
t1=t2;
t2=display;
++count;
printf("%d+",display);
}
return 0;
}

Output
Enter number of terms: 10
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+
Suppose, instead of number of terms, you want to display the Fibonacci series util the term
is less than certain number entered by user. Then, this can be done using source code
below:
/* Displaying Fibonacci series up to certain number entered by user. */
#include <stdio.h>
int main()
{
int t1=0, t2=1, display=0, num;

printf("Enter an integer: ");


scanf("%d",&num);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
display=t1+t2;
while(display<num)
{
printf("%d+",display);
t1=t2;
t2=display;
display=t1+t2;
}
return 0;

Source Code to Check Character is an alphabet or


not
/* C programming code to check whether a character is alphabet or not.*/
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}

When a character is stored in a variable, ASCII value of that character is stored instead of
that character itself. For example: If 'a' is stored in a variable, ASCII value of 'a' which is 97
is stored. If you see the ASCII table , the lowercase alphabets are from 97 to 122 and
uppercase letter are from 65 to 90. If the ASCII value of number stored is between any of
these two intervals then, that character will be an alphabet. In this program, instead of
number 97, 122, 65 and 90; we have used 'a', 'z', 'A' and 'Z' respectively which is basically
the same thing.

Source Code to Convert Binary to Octal and Vice


Versa
/* C programming source code to convert either binary to octal or octal to binary
according to data entered by user. */
#include <stdio.h>
#include <math.h>
int binary_octal(int n);
int octal_binary(int n);

int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'o' to convert binary to octal.\n" );
printf("2. Enter alphabet 'b' to convert octal to binary.\n" );
scanf("%c",&c);
if ( c=='o' || c=='O')
{
printf("Enter a binary number: ");
scanf("%d",&n);
printf("%d in binary = %d in octal", n, binary_octal(n));
}
if ( c=='b' || c=='B')
{
printf("Enter a octal number: ");
scanf("%d",&n);
printf("%d in octal = %d in binary",n, octal_binary(n));
}
return 0;
}
int binary_octal(int n) /* Function to convert binary to octal. */
{
int octal=0, decimal=0, i=0;
while(n!=0)
{
decimal+=(n%10)*pow(2,i);
++i;
n/=10;
}
/*At this point, the decimal variable contains corresponding decimal value of binary
number. */
i=1;
while (decimal!=0)
{
octal+=(decimal%8)*i;
decimal/=8;
i*=10;
}
return octal;
}
int octal_binary(int n) /* Function to convert octal to binary.*/
{
int decimal=0, binary=0, i=0;
while (n!=0)
{
decimal+=(n%10)*pow(8,i);
++i;
n/=10;
}
/* At this point, the decimal variable contains corresponding decimal value of that
octal number. */

i=1;
while(decimal!=0)
{
binary+=(decimal%2)*i;
decimal/=2;
i*=10;
}
return binary;

Source Code to Display Factors of a Number


/* C to find and display all the factors of a number entered by an user.. */
#include <stdio.h>
int main()
{
int n,i;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factors of %d are: ", n);
for(i=1;i<=n;++i)
{
if(n%i==0)
printf("%d ",i);
}
return 0;
}

In this program, an integer entered by user is stored in variable n. Then, for loop is
executed with initial condition i=1 and checked whether n is perfectly divisible
by i or not. If n is perfectly divisible by i then, i will be the factor of n. In each
iteration, the value of i is updated(increased by 1). This process goes not until test
condition i<=n becomes false,i.e., this program checks whether number entered by
user n is perfectly divisible by all numbers from 1 to n and all displays factors of that

C program to display its own source code using


__FILE__
number.

#include <stdio.h>
int main() {
FILE *fp;
char c;
fp = fopen(__FILE__,"r");
do {
c = getc(fp);
putchar(c);
}
while(c != EOF);
fclose(fp);
return 0;
}

This program displays the content of this particular C programming file(source code)
because __FILE__ contains the location of this C programming file in a string.
A predefined macro __FILE__ contains the location of a C programming file, it is working
on. For example:
#include <stdio.h>
int main(){
printf("%s",__FILE__);
}

C program to Check Prime Number


/* C program to check whether a number is prime or not. */
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}

Output
Enter a positive integer: 29
29 is a prime number.
This program takes a positive integer from user and stores it in variable n. Then, for loop is
executed which checks whether the number entered by user is perfectly divisible by i or not
starting with initial value of i equals to 2 and increasing the value of i in each iteration. If the

number entered by user is perfectly divisible by i then, flag is set to 1 and that number will
not be a prime number but, if the number is not perfectly divisible by i until test
condition i<=n/2 is true means, it is only divisible by 1 and that number itself and that
number is a prime number. C program to Check Whether a Number can be Express as
Sum of Two Prime Numbers

#include <stdio.h>
int prime(int n);
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
if (prime(i)!=0)
{
if ( prime(n-i)!=0)
{
printf("%d = %d + %d\n", n, i, n-i);
flag=1;
}
}
}
if (flag==0)
printf("%d can't be expressed as sum of two prime numbers.",n);
return 0;

}
int prime(int n)
/* Function to check prime number */
{
int i, flag=1;
for(i=2; i<=n/2; ++i)
if(n%i==0)
flag=0;
return flag;
}

C Program to Check Whether a Number is


Positive or Negative
#include <stdio.h>
int main()
{
float num;
printf("Enter a number: ");
scanf("%f",&num);
if (num<=0)

{
if (num==0)
printf("You entered zero.");
else
printf("%.2f is negative.",num);
}
else
printf("%.2f is positive.",num);
return 0;
}
/* C programming code to check whether a number is negative or positive or zero
using nested if...else statement. */
#include <stdio.h>
int main()
{
float num;
printf("Enter a number: ");
scanf("%f",&num);
if (num<0)
/* Checking whether num is less than 0*/
printf("%.2f is negative.",num);
else if (num>0) /* Checking whether num is greater than zero*/
printf("%.2f is positive.",num);
else
printf("You entered zero.");
return 0;
}

Das könnte Ihnen auch gefallen