C Programming Examples
C Programming Examples
while (TRUE)
{
printf("Hello World\n");
}
return 0;
}
While loop will execute forever until it is terminated, to terminate press (Ctrl + C) in windows
operating system.
2.C program print integer
This c program ask user to input an integer and then prints it. Input is done using scanf function
and number is printed on screen using printf.
C programming code
#include <stdio.h>
int main()
{
int a;
printf("Enter an integer\n");
scanf("%d", &a);
printf("Integer that you have entered is %d\n", a);
return 0;
}
Download integer program.
Output of program:
In c language we have data type for different types of data, for integer data it is int, for character
date char, for floating point data it's float and so on. For large integers you can use long or long
long data type. To store integers which are greater than 2^18-1 which is the range of long long
data type you may use strings. In the below code we store an integer in a string and then display
it.
C program to store integer in a string
#include <stdio.h>
int main ()
{
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
printf("%s", n);
return 0;
}
Output of program:
Input an integer
13246523123156432123154131212341564313219
13246523123156432123154131212341564313219
Advantage of using string is that we can store very very large integers. C programming language
does not has a built in type to handle large numbers.
3.C program to add two numbers
C program to add two numbers: This c language program perform the basic arithmetic
operation of addition on two numbers and then prints the sum on the screen. For example if the
user entered two numbers as 5, 6 then 11 (5 + 6) will be printed on the screen.
C programming code
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
Output of program:
c = a + b;
printf("(%d) + (%d) = (%d)\n", a, b, c);
printf("Do you wish to add more numbers (y/n)\n");
scanf("%c", &ch);
if (ch == 'y' || ch == 'Y')
continue;
else
break;
}
return 0;
}
Output of program:
Inut two integers
2 6
(2) + (6) = (8)
Do you wish to add more
y
Inut two integers
2 -6
(2) + (-6) = (-4)
Do you wish to add more
y
Inut two integers
-5 3
(-5) + (3) = (-2)
Do you wish to add more
y
Inut two integers
-5 -6
(-5) + (-6) = (-11)
Do you wish to add more
n
numbers (y/n)
numbers (y/n)
numbers (y/n)
numbers (y/n)
}
We have used long data type as it can handle large numbers, if you want to add still larger
numbers which doesn't fit in long range then use array, string or other data structure.
4. C program to check odd or even
C program to check odd or even: We will determine whether a number is odd or even by using
different methods all are provided with a code in c language. As you have study in mathematics
that in decimal number system even numbers are divisible by 2 while odd are not so we may use
modulus operator(%) which returns remainder, For example 4%3 gives 1 ( remainder when four
is divided by three). Even numbers are of the form 2*p and odd are of the form (2*p+1) where p
is is an integer.
C program to check odd or even using modulus operator
#include <stdio.h>
int main()
{
int n;
printf("Enter an integer\n");
scanf("%d", &n);
if (n%2 == 0)
printf("Even\n");
else
printf("Odd\n");
return 0;
}
We can use bitwise AND (&) operator to check odd or even, as an example consider binary of 7
(0111) when we perform 7 & 1 the result will be one and you may observe that the least
significant bit of every odd number is 1, so ( odd_number & 1 ) will be one always and also
( even_number & 1 ) is zero.
}
In c programming language when we divide two integers we get an integer result, For example
the result of 7/3 will be 2. So we can take advantage of this and may use it to find whether the
number is odd or even. Consider an integer n we can first divide by 2 and then multiply it by 2 if
the result is the original number then the number is even otherwise the number is odd. For
example 11/2 = 5, 5*2 = 10 (which is not equal to eleven), now consider 12/2 = 6 and 6*2 = 12
(same as original number). These are some logic which may help you in finding if a number is
odd or not.
5. C program to perform addition, subtraction, multiplication and division
C program to perform basic arithmetic operations which are addition, subtraction,
multiplication and division of two numbers. Numbers are assumed to be integers and will be
entered by the user.
C programming code
#include <stdio.h>
int main()
{
int first, second, add, subtract, multiply;
float divide;
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second;
//typecasting
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %.2f\n",divide);
return 0;
}
Download Arithmetic operations program.
Output of program:
In c language when we divide two integers we get integer result for example 5/2 evaluates to 2.
As a general rule integer/integer = integer and float/integer = float or integer/float = float. So
we convert denominator to float in our program, you may also write float in numerator. This
explicit conversion is known as typecasting.
6. C program to check whether input alphabet is a vowel or not
This code checks whether an input alphabet is a vowel or not. Both lower-case and upper-case
are checked.
C programming code
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", ch);
return 0;
}
Output of program:
return 0;
}
Download Leap year program.
Output of program:
Please read the leap year article at Wikipedia, it will help you to understand the program. This
code is based on Gregorian Calendar.
8. Add digits of number in c
C program to add digits of a number: Here we are using modulus operator(%) to extract
individual digits of number and adding them.
C programming code
#include <stdio.h>
int main()
}
If you wish you can modify input variable (n) and do not use an additional variable (t) but it is
not recommended.
Output of program:
int main()
{
int c, sum, t;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
sum = c = 0;
while (n[c] != '\0') {
t
= n[c] - '0'; // Converting character to integer
sum = sum + t;
c++;
}
printf("Sum of digits of %s = %d\n", n, sum);
return 0;
}
An advantage of this method is that input integer can be very large which may not be stored in
int or long long data type see an example below in output.
Output of program:
Input an integer
123456789123456789123456789
Sum of digits of 123456789123456789123456789 = 135
Add digits using recursion
#include <stdio.h>
int add_digits(int);
int main()
{
int n, result;
scanf("%d", &n);
result = add_digits(n);
printf("%d\n", result);
}
return 0;
int add_digits(int n) {
static int sum = 0;
if (n == 0) {
return 0;
}
sum = n%10 + add_digits(n/10);
return sum;
}
Static variable sum is used and is initialized to 0, it' value will persists after function calls i.e. it is
initialized only once when a first call to function is made.
9. Factorial program in c
Factorial program in c: c code to find and print factorial of a number, three methods are given,
first one uses for loop, second uses a function to find factorial and third using recursion.
Factorial is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.
Factorial program in c using for loop
Here we find factorial using for loop.
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
Download Factorial program.
Output of code:
return result;
return 0;
}
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
Recursion is a technique in which a function calls itself, for example in above code factorial
function is calling itself. To solve a problem using recursion you must first express its solution in
recursive form.
10. C program to find hcf and lcm
C program to find hcf and lcm: The code below finds highest common factor and least common
multiple of two integers. HCF is also known as greatest common divisor(GCD) or greatest
common factor(gcf).
C programming code
#include <stdio.h>
int main() {
int a, b, x, y, t, gcd, lcm;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
a = x;
b = y;
while
t =
b =
a =
}
(b != 0) {
b;
a % b;
t;
gcd = a;
lcm = (x*y)/gcd;
printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
return 0;
}
Download HCF and LCM program.
Output of program:
return 0;
return 0;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
Download Decimal binary program.
Output of program:
Above code only prints binary of integer, but we may wish to perform operations on binary so in
the code below we are storing the binary in a string. We create a function which returns a
pointer to string which is the binary of the number passed as argument to the function.
C code to store decimal to binary conversion in a string
#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, t);
free(pointer);
}
return 0;
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if ( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 31 ; c >= 0 ; c-- )
{
d = n >> c;
if ( d & 1 )
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return
pointer;
}
Memory is allocated dynamically because we can't return a pointer to a local variable (character
array in this case). If we return a pointer to local variable then program may crash or we get
incorrect result.
12. C program to find ncr and npr
C program to find nCr and nPr: This code calculate nCr which is n!/(r!*(n-r)!) and nPr = n!/(nr)!
C program to find nCr using function
#include <stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
int main()
{
int n, r;
long ncr, npr;
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
return 0;
return result;
return result;
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Download NCR and NPR program.
Output of program:
return result;
ll factorial(int n) {
int c;
ll result = 1;
for (c = 1; c <= n; c++)
result = result*c;
}
return result;
}
You can use long int data type for sum variable.
Download Add n numbers program.
Output of program:
scanf("%d", &n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
sum = sum + array[c];
}
printf("Sum = %d\n",sum);
return 0;
}
The advantage of using array is that we have a record of numbers inputted by user and can use
them further in program if required and obviously storing numbers will require additional
memory.
Add n numbers using recursion
#include <stdio.h>
long calculateSum(int [], int);
int main()
{
int n, c, array[100];
long result;
scanf("%d", &n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
result = calculateSum(array, n);
printf("Sum = %ld\n", result);
}
return 0;
}
Download Swap numbers program.
Output of program:
int a, b;
printf("Enter two integers to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}
To understand above logic simply choose a as 7 and b as 9 and then do what is written in
program. You can choose any other combination of numbers as well. Sometimes it's a good way
to understand a program.
Swap two numbers using pointers
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
a = &x;
b = &y;
temp = *b;
*b
= *a;
*a
= temp;
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
Swapping numbers using call by reference
In this method we will make a function to swap numbers.
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b
= *a;
*a
= temp;
number. To invert number look at it and write it from opposite direction or the output of code is
a number obtained by writing original number from right to left. To reverse or invert large
numbers use long data type or long long data type if your compiler supports it, if you still have
large numbers then use strings or other data structure.
C programming code
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n
= n/10;
}
printf("Reverse of entered number is = %d\n", reverse);
return 0;
}
Download Reverse number program.
Output of program:
printf("%ld\n", r);
}
return 0;
long reverse(long n) {
static long r = 0;
if (n == 0)
return 0;
r = r * 10;
r = r + n % 10;
reverse(n/10);
return r;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
Download Palindrome number program.
Output of program:
}
Download Stars pyramid program.
Output of program:
For more patterns or shapes on numbers and characters see comments below and also see codes
on following pages:
Floyd triangle
Pascal triangle
Consider the pattern
*
**
***
****
*****
to print above pattern see the code below:
#include <stdio.h>
int main()
{
int n, c, k;
}
Using these examples you are in a better position to create your desired pattern for yourself.
Creating a pattern involves how to use nested loops properly, some pattern may involve
alphabets or other special characters. Key aspect is knowing how the characters in pattern
changes.
C pattern programs
Pattern:
*
*A*
*A*A*
*A*A*A*
C pattern program of stars and alphabets:
#include<stdio.h>
main()
{
int n, c, k, space, count = 1;
printf("Enter number of rows\n");
scanf("%d",&n);
space = n;
for ( c = 1 ; c <= n ; c++)
{
for( k = 1 ; k < space ; k++)
printf(" ");
for ( k = 1 ; k <= c ; k++)
printf("*");
if ( c > 1 && count < c)
{
printf("A");
count++;
}
}
printf("\n");
space--;
count = 1;
}
return 0;
}
Pattern:
1
232
34543
4567654
567898765
C program:
#include<stdio.h>
main()
{
int n, c, d, num = 1, space;
scanf("%d",&n);
space = n - 1;
for ( d = 1 ; d <= n ; d++ )
{
num = d;
for ( c = 1 ; c <= space ; c++ )
printf(" ");
space--;
for ( c = 1 ; c <= d ; c++ )
{
printf("%d", num);
num++;
}
num--;
num--;
for ( c = 1 ; c < d ; c++)
{
printf("%d", num);
num--;
}
printf("\n");
}
return 0;
}
17. C program to print diamond pattern
Diamond pattern in c: This code print diamond pattern of stars. Diamond shape is as follows:
*
***
*****
***
*
C programming code
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("\n");
}
return 0;
}
Download Diamond program.
Output of program:
scanf("%d", &rows);
print(rows);
}
return 0;
printf("\n");
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}
Download Prime number program.
Output of program:
main()
{
int n, c = 2;
printf("Enter a number to check if it is prime\n");
scanf("%d",&n);
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("%d is not prime.\n", n);
break;
}
}
if ( c == n )
printf("%d is prime.\n", n);
return 0;
}
C program for prime number using function
#include<stdio.h>
int check_prime(int);
main()
{
int n, result;
printf("Enter an integer to check whether it is prime or not.\n");
scanf("%d",&n);
result = check_prime(n);
if ( result == 1 )
printf("%d is prime.\n", n);
else
printf("%d is not prime.\n", n);
}
return 0;
int check_prime(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
if ( a%c == 0 )
return 0;
}
if ( c == a )
return 1;
}
There are many logic to check prime numbers, one given below is more efficient then above
method.
for ( c = 2 ; c <= (int)sqrt(n) ; c++ )
Only checking from 2 to square root of number is sufficient.
There are many more efficient logic available.
19. Armstrong number c program
Armstrong number c program: c programming code to check whether a number is Armstrong or
not. Armstrong number is a number which is equal to sum of digits raise to the power total
number of digits in the number. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634,
8208 etc. Read more about Armstrong numbers at Wikipedia. We will consider base 10
numbers in our program. Algorithm to check Armstrong is: First we calculate number of digits
in our program and then compute sum of individual digits raise to the power number of digits. If
this sum equals input number then number is Armstrong otherwise not an Armstrong number.
Examples:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096).
1741725 = 1^7 + 7^7 + 4^7 + 1^7 + 7^7 + 2^7 +5^7 (1 + 823543 + 16384 + 1 + 823543 +128 +
78125)
C programming code
#include <stdio.h>
int power(int, int);
int main()
{
int n, sum = 0, temp, remainder, digits = 0;
printf("Input an integer\n");
scanf("%d", &n);
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
printf("%d is an Armstrong number.\n", n);
else
printf("%d is not an Armstrong number.\n", n);
}
return 0;
return 0;
number is Armstrong and 0 otherwise. If you are not familiar with Armstrong numbers
see Check Armstrong number program.
C programming code
#include <stdio.h>
int check_armstrong(int);
int power(int, int);
int main () {
int c, a, b;
printf("Input two integers\n");
scanf("%d%d", &a, &b);
for (c = a; c <= b; c++) {
if (check_armstrong(c) == 1)
printf("%d\n", c);
}
return 0;
}
int check_armstrong(int n) {
long long sum = 0, temp;
int remainder, digits = 0;
temp = n;
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
return 1;
else
return 0;
int
power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Download Generate Armstrong numbers program.
Output of program:
In the sample output we are printing Armstrong numbers in range [0, 1000000].
21. Fibonacci series in c
Fibonacci series in c programming: c program for Fibonacci series without and with recursion.
Using the code below you can print as many numbers of terms of series as desired. Numbers of
Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2,
3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms,
For example 8 = 3 + 5 (addition of 3, 5). This sequence has many applications in mathematics
and Computer Science.
Fibonacci series in c using for loop
/* Fibonacci Series c language */
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
return 0;
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Recursion method is less efficient as it involves function calls which uses stack, also there are
chances of stack overflow if function is called frequently for calculating larger Fibonacci
numbers.
22. C program to print Floyd's triangle
C program to print Floyd's triangle:- This program prints Floyd's triangle. Number of rows of
Floyd's triangle to print is entered by the user. First four rows of Floyd's triangle are as follows :1
23
456
7 8 9 10
It's clear that in Floyd's triangle nth row contains n numbers.
C programming code
#include <stdio.h>
int main()
{
int n, i,
c, a = 1;
}
Download Floyd triangle program.
Output of program:
c, a = 1;
1
11
121
1331
Pascal triangle in c
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal
triangle\n");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
for (c = 0 ; c <= i; c++)
printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("\n");
}
}
return 0;
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Download Pascal triangle program.
Output of program:
For more patterns or shapes on numbers and characters see codes on following pages:
Patterns programs
Floyd triangle
24. C program to add two numbers using pointers
This program performs addition of two numbers using pointers. In our program we have two
two integer variables x, y and two pointer variables p and q. Firstly we assign the addresses of x
and y to p and q respectively and then assign the sum of x and y to variable sum. Note that & is
address of operator and * is value at address operator.
C programming code
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;
}
Download Add integers using pointers program.
Output of program:
return index;
return index;
Output of program:
Output of code:
return 0;
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
C program for linear search
Download Binary search program.
Output of program:
Binary search is faster than linear search but list should be sorted, hashing is faster than binary
search and perform searches in constant time.
29. C program to reverse an array
C program to reverse an array: This program reverses the array elements. For example if a is an
array of integers with three elements such that
a[0] = 1
a[1] = 2
a[2] = 3
Then on reversing the array will be
a[0] = 3
a[1] = 2
a[0] = 1
Given below is the c code to reverse an array.
C programming code
#include <stdio.h>
int main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
/*
* Copying elements into array b starting from end of array a
*/
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
/*
* Copying reversed array into original.
* Here we are modifying original array, this is optional.
*/
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array is\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
return 0;
}
Download Reverse array program.
Output of program:
end--;
Output of program:
}
Download Delete element from array program.
Output of program:
If the arrays are not sorted then you can sort them first and then use the above merge function,
another method is to merge them and then sort the array. Sorting two smaller arrays will take
less time as compared to sorting a big array. Merging two sorted array is used in merge sort
algorithm.
33. C program for bubble sort
C program for bubble sort: c programming code for bubble sort to sort numbers or arrange them
in ascending order. You can easily modify it to print numbers in descending order.
Bubble sort algorithm in c
/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
if (array[d]
{
swap
array[d]
array[d+1]
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Download Bubble sort program.
Output of program:
return 0;
}
You can also sort strings using Bubble sort, it is less efficient as its average and worst case
complexity is high, there are many other fast sorting algorithms.
34. insertion sort in c
Insertion sort in c: c program for insertion sort to sort numbers. This code implements insertion
sort algorithm to arrange numbers of an array in ascending order. With a little modification it
will arrange numbers in descending order.
Insertion sort algorithm implementation in c
/* insertion sort ascending order */
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
d--;
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
return 0;
}
Download Insertion sort program.
Output of program:
Output of program:
246
When we transpose a matrix then the order of matrix changes, but for a square matrix order
remains same.
C programming code
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of matrix\n");
for (c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d",&matrix[c][d]);
for (c = 0; c < m; c++)
for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
printf("Transpose of entered matrix :-\n");
for (c = 0; c < n; c++) {
for (d = 0; d < m; d++)
printf("%d\t",transpose[c][d]);
printf("\n");
}
return 0;
}
Download Transpose Matrix program.
Output of program:
m; c++) {
< q; d++) {
k < p; k++) {
+ first[c][k]*second[k][d];
multiply[c][d] = sum;
sum = 0;
}
printf("\n");
}
return 0;
}
Download Matrix multiplication program.
A 3 X 3 matrix multiply in c is shown as example below.
Matrices are frequently used while doing programming and are used to represent graph data
structure, in solving system of linear equations and many more. Lot of research is being done on
how to multiply matrices using minimum number of operations. You can also implement it
using pointers.
40. C program print string
This program print a string. String can be printed by using various functions such as printf,
puts.
C programming code
#include <stdio.h>
int main()
{
char array[20] = "Hello World";
printf("%s\n",array);
return 0;
}
To input a string we use scanf function.
C programming code
#include <stdio.h>
int main()
{
char array[100];
printf("Enter a string\n");
scanf("%s", array);
}
Note that scanf can only input single word strings, to receive strings containing spaces use gets
function.
C program to print string using recursion
#include <stdio.h>
void print(char*);
int main() {
char s[100];
gets(s);
print(s);
return 0;
}
void print(char *t) {
if (*t == '\0')
return;
printf("%c", *t);
print(++t);
}
Print string using loop
We print string using for loop by printing individual characters of string.
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
int c, l;
gets(s);
l = strlen(s);
for (c = 0; c < l; c++)
printf("%c", s[c]);
return 0;
}
41. String length
This program prints length of string, for example consider the string "c programming" it's length
is 13. Null character is not counted when calculating string length. To find string length we use
strlen function of string.h.
C program to find string length
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate it's length\n");
gets(a);
length = strlen(a);
printf("Length of entered string is = %d\n",length);
return 0;
}
Download String length program.
Output of program:
return c;
return c;
int flag;
char a[1000], b[1000];
printf("Input first string\n");
gets(a);
printf("Input second string\n");
gets(b);
flag = compare_strings(a, b);
if (flag == 0)
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
int compare_strings(char a[], char b[])
{
int c = 0;
while (a[c] == b[c]) {
if (a[c] == '\0' || b[c] == '\0')
break;
c++;
}
if (a[c] == '\0' && b[c] == '\0')
return 0;
else
return -1;
}
C program to compare two strings using pointers
In this method we will make our own function to perform string comparison, we will use
character pointers in our function to manipulate string.
#include<stdio.h>
int compare_string(char*, char*);
int main()
{
char first[1000], second[1000], result;
printf("Input first string\n");
gets(first);
printf("Input second string\n");
gets(second);
result = compare_string(first, second);
if (result == 0)
printf("Both strings are same.\n");
else
printf("Entered strings are not equal.\n");
return 0;
return 0;
}
Output of program:
return 0;
source++;
target++;
}
*target = '\0';
}
44. C program to concatenate strings
This program concatenates strings, for example if the first string is "c " and second string is
"program" then on concatenating these two strings we get the string "c program". To
concatenate two strings we use strcat function of string.h, to concatenate without using library
function see another code below which uses pointers.
C programming code
#include <stdio.h>
#include <string.h>
int main()
{
char a[1000], b[1000];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcat(a,b);
printf("String obtained on concatenation is %s\n",a);
return 0;
}
Download String Concatenation program.
Output of program:
return 0;
}
The first for loop in concatenate function is calculating string length so you can also use strlen
function if you wish.
String concatenation using pointers
#include <stdio.h>
void concatenate_string(char*, char*);
int main()
{
char original[100], add[100];
strrev(arr);
printf("Reverse of entered string is \n%s\n",arr);
return 0;
}
Download Reverse string program.
Output of program:
return 0;
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
}
return 0;
begin++;
end--;
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer + c) != '\0' )
c++;
return c;
return 0;
}
In recursion method we swap characters at the begin and at the end and then move towards the
middle of the string. This method is inefficient due to repeated function calls but useful in
practicing recursion.
46.C palindrome program, c program for palindrome
C program for palindrome or palindrome in c programming: palindrome program in c language,
c code to check if a string is a palindrome or not and for palindrome number. This program
works as follows :- at first we copy the entered string into a new string, and then we reverse the
new string and then compares it with original string. If both of them have same sequence of
characters i.e. they are identical then the entered string is a palindrome otherwise not. To
perform copy, reverse and compare operations we use strcpy, strrev and strcmp functions of
string.h respectively, if you do not wish to use these functions see c programming code for
palindrome without using string functions. Some palindrome strings examples are "a", dad",
"radar", "madam", "abcba" etc.
Palindrome number in c
#include <stdio.h>
main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp
= temp/10;
}
if (n == reverse)
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
}
return 0;
int main()
{
char string[100];
int result;
printf("Input a string\n");
gets(string);
result = is_palindrome(string);
if ( result == 1 )
printf("\"%s\" is a palindrome string.\n", string);
else
printf("\"%s\" is not a palindrome string.\n", string);
}
return 0;
return length;
}
void copy_string(char *target, char *source)
{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}
void reverse_string(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c =
{
temp =
*end =
*begin
begin++;
end--;
}
return 0;
}
int toString(char a[]) {
int c, sign, offset, n;
if (a[0] == '-') {
sign = -1;
}
if (sign == -1) {
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
Similarly you can convert string to long.
Output of program:
//not a vowel
t[j] = '\0';
strcpy(s, t);
return 0;
int check_vowel(char c)
{
switch(c) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1;
default:
return 0;
}
}
Output of program:
printf("Enter a string\n");
gets(string);
temp = string;
pointer = (char*)malloc(100);
if( pointer == NULL )
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
start = pointer;
while(*temp)
{
ch = *temp;
if ( !check_vowel(ch) )
{
*pointer = ch;
pointer++;
}
temp++;
}
*pointer = '\0';
*/
pointer = start;
strcpy(string, pointer); /* If you wish to convert original string
free(pointer);
printf("String after removing vowel is \"%s\"\n", string);
return 0;
int check_vowel(char a)
{
if ( a >= 'A' && a <= 'Z' )
a = a + 'a' - 'A';
if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return TRUE;
return FALSE;
}
}
C substring program output:
return 0;
while (c < l) {
sub[c] = s[p+c-1];
c++;
}
sub[c] = '\0';
return 0;
int main () {
int flag;
char s1[1000], s2[1000];
printf("Input first string\n");
gets(s1);
printf("Input second string\n");
gets(s2);
/** Passing smaller length string first */
if (strlen(s1) < strlen(s2))
flag = check_subsequence(s1, s2);
else
flag = check_subsequence(s2, s1);
if (flag)
printf("YES\n");
else
printf("NO\n");
return 0;
}
int check_subsequence (char a[], char b[]) {
int c, d;
c = d = 0;
while (a[c] != '\0') {
while ((a[c] != b[d]) && b[d] != '\0') {
d++;
}
if (b[d] == '\0')
break;
d++;
c++;
}
if (a[c] == '\0')
return 1;
else
return 0;
}
Output of program:
Input first string
computer science is awesome
x = ch - 'a';
for (c = 0; c < no[x]; c++)
{
output[t] = ch;
t++;
}
}
output[t] = '\0';
printf("%s\n", output);
return 0;
}
Output of program:
return 0;
result = (char*)malloc(length+1);
pointer = s;
for ( ch = 'a' ; ch <= 'z' ; ch++ )
{
for ( c = 0 ; c < length ; c++ )
{
if ( *pointer == ch )
{
*(result+d) = *pointer;
d++;
}
pointer++;
}
pointer = s;
}
*(result+d) = '\0';
strcpy(s, result);
free(result);
}
Download Sort string program.
52. C program remove spaces, blanks from a string
C code to remove spaces or excess blanks from a string, For example consider the string
"c programming"
There are two spaces in this string, so our program will print a string
"c programming". It will remove spaces when they occur more than one time consecutively in
string anywhere.
C programming code
#include <stdio.h>
int main()
{
char text[1000], blank[1000];
int c = 0, d = 0;
printf("Enter some text\n");
gets(text);
while (text[c] != '\0') {
if (text[c] == ' ') {
int temp = c + 1;
if (text[temp] != '\0') {
while (text[temp] == ' ' && text[temp] != '\0') {
}
blank[d] = text[c];
c++;
d++;
}
blank[d] = '\0';
printf("Text after removing blanks\n%s\n", blank);
return 0;
}
If you want you can copy blank into text string so that original string is modified.
Download Remove spaces program.
Output of program:
free(r);
}
return 0;
return start;
char string[1000];
printf("Input a string to convert to lower case\n");
gets(string);
printf("Input string in lower case: \"%s\"\n",strlwr(string));
return
0;
strupr in c
#include <stdio.h>
#include <string.h>
int main()
{
char string[1000];
printf("Input a string to convert to upper case\n");
gets(string);
printf("Input string in upper case: \"%s\"\n",strupr(string));
return
0;
}
Change string to upper case without strupr
#include <stdio.h>
void upper_string(char []);
int main()
{
char string[100];
printf("Enter a string to convert it into upper case\n");
gets(string);
upper_string(string);
printf("Entered string in upper case is \"%s\"\n", string);
return 0;
}
void upper_string(char s[]) {
int c = 0;
}
You can also implement functions using pointers.
printf("Input a string\n");
gets(s);
while (s[c] != '\0') {
ch = s[c];
if (ch >= 'A' && ch <= 'Z')
s[c] = s[c] + 32;
else if (ch >= 'a' && ch <= 'z')
s[c] = s[c] - 32;
c++;
}
printf("%s\n", s);
return 0;
}
Output of program:
Input a string
abcdefghijklmnopqrstuvwxyz{0123456789}ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ{0123456789}abcdefghijklmnopqrstuvwxyz
If a digit or special character is present in string it is left as it is.
54. C program to swap two strings
C program to swap strings i.e. contents of two strings are interchanged.
C programming code
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main()
{
char first[100], second[100], *temp;
printf("Enter the first string\n");
gets(first);
printf("Enter the second string\n");
gets(second);
printf("\nBefore Swapping\n");
printf("First string: %s\n",first);
printf("Second string: %s\n\n",second);
temp = (char*)malloc(100);
strcpy(temp,first);
strcpy(first,second);
strcpy(second,temp);
printf("After Swapping\n");
printf("First string: %s\n",first);
printf("Second string: %s\n",second);
return 0;
}
Download Swap strings program.
Output of program:
c++;
Did you notice that string in the output of program contains every alphabet at least once.
Output of progran:
We do not pass no of elements of array count[] to function find_frequency as they will always be
26. But you can pass if you wish to do so.
56. Anagram in c
Anagram in c: c program to check whether two strings are anagrams or not, string is assumed to
consist of alphabets only. Two words are said to be anagrams of each other if the letters from
one word can be rearranged to form the other word. From the above definition it is clear that
two strings are anagrams if all characters in both strings occur same number of times. For
example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one
time in both strings. Our algorithm tries to find how many times characters appear in the strings
and then comparing their corresponding counts.
C anagram programming code
#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
return 0;
Output of program:
There are blank lines present at end of file. In our program we have opened only one file but you
can open multiple files in a single program and in different modes as desired. File handling is
very important when we wish to store data permanently on a storage device. All variables and
data of program is lost when program exits so if that data is required later we need to use files.
58. C program to copy files
C program to copy files: This program copies a file, firstly you will specify the file to copy and
then you will enter the name of target file, You will have to mention the extension of file also. We
will open the file that we wish to copy in read mode and target file in write mode.
C programming code
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, source_file[20], target_file[20];
FILE *source, *target;
printf("Enter name of file to copy\n");
gets(source_file);
source = fopen(source_file, "r");
if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
printf("Enter name of target file\n");
gets(target_file);
target = fopen(target_file, "w");
if( target == NULL )
{
fclose(source);
}
Download File copy program.
Output of program: This c program merges files and stores their contents in another file. The
files which are to be merged are opened in read mode and the file which contains content of
both the files is opened in write mode. To merge two files first we open a file and read it
character by character and store the read contents in another file then we read the contents of
another file and store it in file, we read two files until EOF (end of file) is reached.
C programming code
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);
printf("Enter name of file which will store contents of two
files\n");
gets(file3);
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
Download merge files program.
Output of program:
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
Download merge files program.
Output of program:
{
}
printf("%s\n",a.ff_name);
done = findnext(&a);
getch();
return 0;
}
Obviously you will get a different output when you will execute this file on your computer.
61. C program to delete a file
This c program deletes a file which is entered by the user, the file to be deleted should be present
in the directory in which the executable file of this program is present. Extension of the file
should also be entered, remove macro is used to delete the file. If there is an error in deleting the
file then an error will be displayed using perror function.
C programming code
#include<stdio.h>
main()
{
int status;
char file_name[25];
printf("Enter the name of file you wish to delete\n");
gets(file_name);
status = remove(file_name);
if( status == 0 )
printf("%s file deleted successfully.\n",file_name);
else
{
printf("Unable to delete the file\n");
perror("Error");
}
return 0;
}
Download Delete file program executable.
Output of program:
Deleted file doesn't go to trash or recycle bin so you may not be able to recover it. Deleted files
can be recovered using special recovery software if the files are not overwritten on the storage
medium.
62. C program to generate random numbers
This c program generates pseudo random numbers using rand and random function(Turbo C
compiler only). As the random numbers are generated by an algorithm used in a function they
are pseudo random, this is the reason why pseudo word is used. Function rand() returns a
pseudo random number between 0 and RAND_MAX. RAND_MAX is a constant which is
platform dependent and equals the maximum value returned by rand function.
C programming code using rand
We use modulus operator in our program. If you evaluate a % b where a and b are integers then
result will always be less than b for any set of values of a and b. For example
For a = 1243 and b = 100
a % b = 1243 % 100 = 43
For a = 99 and b = 100
a % b = 99 % 100 = 99
For a = 1000 and b = 100
a % b = 1000 % 100 = 0
In our program we print pseudo random numbers in range [0, 100]. So we calculate rand() %
100 which will return a number in [0, 99] so we add 1 to get the desired range.
#include <stdio.h>
#include <stdlib.h>
int main() {
int c, n;
printf("Ten random numbers in [1,100]\n");
for (c = 1; c <= 10; c++) {
n = rand() % 100 + 1;
printf("%d\n", n);
}
return 0;
}
If you rerun this program you will get same set of numbers. To get different numbers every time
you can use: srand(unisgned int seed) function, here seed is an unsigned integer. So you will
need a different value of seed every time you run the program for that you can use current time
which will always be different so you will get a different set of numbers. By default seed = 1 if
you do not use srand function.
C programming code using random function(Turbo C compiler only)
randomize function is used to initialize random number generator. If you don't use it then you
will get same random numbers each time you run the program.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
int n, max, num, c;
printf("Enter the number of random numbers you want\n");
scanf("%d", &n);
printf("Enter the maximum value of random number\n");
scanf("%d", &max);
printf("%d random numbers from 0 to %d are :-\n", n, max);
randomize();
for (c = 1; c <= n; c++)
{
num = random(max);
printf("%d\n",num);
}
getch();
return 0;
struct complex
{
int real, img;
};
int main()
{
struct complex a, b, c;
printf("Enter a and b where a + ib is the first complex
number.\n");
printf("a = ");
scanf("%d", &a.real);
printf("b = ");
scanf("%d", &a.img);
printf("Enter c and d where c + id is the second complex
number.\n");
printf("c = ");
scanf("%d", &b.real);
printf("d = ");
scanf("%d", &b.img);
c.real = a.real + b.real;
c.img = a.img + b.img;
if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di\n", c.real,
c.img);
else
printf("Sum of two complex numbers = %d %di\n", c.real, c.img);
return 0;
}
Download add complex numbers program executable.
Output of c program to add two complex numbers is shown in image below:
}
Download IP address program.
Output of program: ( In Windows 7)
#include <stdio.h>
int main() {
system("shutdown -P now");
return 0;
}
You need to be logged in as root user for above program to execute otherwise you will get the
message shutdown: Need to be root, now specifies that you want to shutdown immediately. '-P'
option specifies you want to power off your machine. You can specify minutes as:
shutdown -P "number of minutes"
For more help or options type at terminal: man shutdown.