0% found this document useful (0 votes)
130 views82 pages

C Programs

This document contains C code examples for various programming concepts like checking vowels, leap year calculation, digit sum, factorial calculation using loops and recursion, binary conversion, reverse number, palindrome checking, Fibonacci series using loops and recursion, and Pascal's triangle. The code snippets demonstrate fundamental programming constructs like conditional statements, loops, functions, and recursion.

Uploaded by

Erwin Marcelo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views82 pages

C Programs

This document contains C code examples for various programming concepts like checking vowels, leap year calculation, digit sum, factorial calculation using loops and recursion, binary conversion, reverse number, palindrome checking, Fibonacci series using loops and recursion, and Pascal's triangle. The code snippets demonstrate fundamental programming constructs like conditional statements, loops, functions, and recursion.

Uploaded by

Erwin Marcelo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Check vowel using if else

1. #include <stdio.h>
2.
3. int main()
4. {
5. char ch;
6.
7. printf("Enter a character\n");
8. scanf("%c", &ch);
9.
10. // Checking both lower and upper case
11.
12. if (ch == 'a' || ch == 'A' || ch == 'e' || ch ==
'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' ||
ch == 'u' || ch == 'U')
13. printf("%c is a vowel.\n", ch);
14. else
15. printf("%c isn't a vowel.\n", ch);
16.
17. return 0;
18. }

C program to check leap year


1.
2. #include <stdio.h>
3.
4. int main()
5. {
6. int year;
7.
8. printf("Enter a year to check if it is a leap
year\n");
9. scanf("%d", &year);
10.
11. if (year%400 == 0) // Exactly divisible by 400
e.g. 1600, 2000
12. printf("%d is a leap year.\n", year);
13. else if (year%100 == 0) // Exactly divisible by
100 and not by 400 e.g. 1900, 2100
14. printf("%d isn't a leap year.\n", year);
15. else if (year%4 == 0) // Exactly divisible by 4
and neither by 100 nor 400 e.g. 2016, 2020
16. printf("%d is a leap year.\n", year);
17. else // Not divisible by 4 or 100 or 400 e.g.
2017, 2018, 2019
18. printf("%d isn't a leap year.\n", year);
19.
20. return 0;
21. }

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. int n, t, sum = 0, remainder;
6.
7. printf("Enter an integer\n");
8. scanf("%d", &n);
9.
10. t = n;
11.
12. while (t != 0)
13. {
14. remainder = t % 10;
15. sum = sum + remainder;
16. t = t / 10;
17. }
18.
19. printf("Sum of digits of %d = %d\n", n, sum);
20.
21. return 0;
22. }

Factorial program in C using a for loop


1. #include <stdio.h>
2.
3. int main()
4. {
5. int c, n, fact = 1;
6.
7. printf("Enter a number to calculate its
factorial\n");
8. scanf("%d", &n);
9.
10. for (c = 1; c <= n; c++)
11. fact = fact * c;
12.
13. printf("Factorial of %d = %d\n", n, fact);
14.
15. return 0;
16. }

C programming code
1. #include <stdio.h>
2.
3. int main() {
4. int a, b, x, y, t, gcd, lcm;
5.
6. printf("Enter two integers\n");
7. scanf("%d%d", &x, &y);
8.
9. a = x;
10. b = y;
11.
12. while (b != 0) {
13. t = b;
14. b = a % b;
15. a = t;
16. }
17.
18. gcd = a;
19. lcm = (x*y)/gcd;
20.
21. printf("Greatest common divisor of %d and %d =
%d\n", x, y, gcd);
22. printf("Least common multiple of %d and %d =
%d\n", x, y, lcm);
23.
24. return 0;
25. }

C program to find hcf and lcm using recursion


1. #include <stdio.h>
2.
3. long gcd(long, long);
4.
5. int main() {
6. long x, y, hcf, lcm;
7.
8. printf("Enter two integers\n");
9. scanf("%ld%ld", &x, &y);
10.
11. hcf = gcd(x, y);
12. lcm = (x*y)/hcf;
13.
14. printf("Greatest common divisor of %ld and %ld =
%ld\n", x, y, hcf);
15. printf("Least common multiple of %ld and %ld =
%ld\n", x, y, lcm);
16.
17. return 0;
18. }
19.
20. long gcd(long a, long b) {
21. if (b == 0) {
22. return a;
23. }
24. else {
25. return gcd(b, a % b);
26. }
27. }
C program to find hcf and lcm using function
1. #include <stdio.h>
2.
3. long gcd(long, long);
4.
5. int main() {
6. long x, y, hcf, lcm;
7.
8. printf("Enter two integers\n");
9. scanf("%ld%ld", &x, &y);
10.
11. hcf = gcd(x, y);
12. lcm = (x*y)/hcf;
13.
14. printf("Greatest common divisor of %ld and %ld =
%ld\n", x, y, hcf);
15. printf("Least common multiple of %ld and %ld =
%ld\n", x, y, lcm);
16.
17. return 0;
18. }
19.
20. long gcd(long x, long y) {
21. if (x == 0) {
22. return y;
23. }
24.
25. while (y != 0) {
26. if (x > y) {
27. x = x - y;
28. }
29. else {
30. y = y - x;
31. }
32. }
33.
34. return x;
35. }
C program to convert decimal to binary
1. #include <stdio.h>
2.
3. int main()
4. {
5. int n, c, k;
6.
7. printf("Enter an integer in decimal number
system\n");
8. scanf("%d", &n);
9.
10. printf("%d in binary number system is:\n", n);
11.
12. for (c = 31; c >= 0; c--)
13. {
14. k = n >> c;
15.
16. if (k & 1)
17. printf("1");
18. else
19. printf("0");
20. }
21.
22. printf("\n");
23.
24. return 0;
25. }

Output of the program:

This code only prints binary of an integer, but we may wish to perform
operations on binary, so in the program 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 an argument to the function.

C code to store decimal to binary conversion in a


string
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. char *decimal_to_binary(int);
5.
6. main()
7. {
8. int n, c, k;
9. char *pointer;
10.
11. printf("Enter an integer in decimal number
system\n");
12. scanf("%d",&n);
13.
14. pointer = decimal_to_binary(n);
15. printf("Binary string of %d is: %s\n", n, t);
16.
17. free(pointer);
18.
19. return 0;
20. }
21.
22. char *decimal_to_binary(int n)
23. {
24. int c, d, count;
25. char *pointer;
26.
27. count = 0;
28. pointer = (char*)malloc(32+1);
29.
30. if (pointer == NULL)
31. exit(EXIT_FAILURE);
32.
33. for (c = 31 ; c >= 0 ; c--)
34. {
35. d = n >> c;
36.
37. if (d & 1)
38. *(pointer+count) = 1 + '0';
39. else
40. *(pointer+count) = 0 + '0';
41.
42. count++;
43. }
44. *(pointer+count) = '\0';
45.
46. return pointer;
47. }

C program to find reverse of a number


1. #include <stdio.h>
2.
3. int main()
4. {
5. int n, reverse = 0;
6.
7. printf("Enter a number to reverse\n");
8. scanf("%d", &n);
9.
10. while (n != 0)
11. {
12. reverse = reverse * 10;
13. reverse = reverse + n%10;
14. n = n/10;
15. }
16.
17. printf("Reverse of entered number is =
%d\n", reverse);
18.
19. return 0;
20. }
Output of program:

Download Reverse number program.

Reverse number C program using recursion


1. #include <stdio.h>
2.
3. long reverse(long);
4.
5. int main()
6. {
7. long n, r;
8.
9. scanf("%ld", &n);
10.
11. r = reverse(n);
12.
13. printf("%ld\n", r);
14.
15. return 0;
16. }
17.
18. long reverse(long n) {
19. static long r = 0;
20.
21. if (n == 0)
22. return 0;
23.
24. r = r * 10;
25. r = r + n % 10;
26. reverse(n/10);
27. return r;
28. }
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 a string
or other data structure.

C program for palindrome number


1. #include <stdio.h>
2.
3. int main()
4. {
5. int n, reverse = 0, t;
6.
7. printf("Enter a number to check if it is a
palindrome or not\n");
8. scanf("%d", &n);
9.
10. t = n;
11.
12. while (t != 0)
13. {
14. reverse = reverse * 10;
15. reverse = reverse + t%10;
16. t = t/10;
17. }
18.
19. if (n == reverse)
20. printf("%d is a palindrome number.\n", n);
21. else
22. printf("%d isn't a palindrome number.\n", n);
23.
24. return 0;
25. }

Output of the program:


Download Palindrome number program.

Function to check palindrome number


1. int check_palindrome(int n) {
2. int t, reverse = 0;
3.
4. t = n;
5.
6. while (t != 0) {
7. reverse = reverse * 10;
8. reverse = reverse + t%10;
9. t = t/10;
10. }
11.
12. if (n == reverse)
13. return 1;
14. else
15. return 0;
16. }

Fibonacci series C program using a for loop


1. /* Fibonacci series program in C language */
2. #include <stdio.h>
3.
4. int main()
5. {
6. int n, first = 0, second = 1, next, c;
7.
8. printf("Enter the number of terms\n");
9. scanf("%d", &n);
10.
11. printf("First %d terms of Fibonacci series
are:\n", n);
12.
13. for (c = 0; c < n; c++)
14. {
15. if (c <= 1)
16. next = c;
17. else
18. {
19. next = first + second;
20. first = second;
21. second = next;
22. }
23. printf("%d\n", next);
24. }
25.
26. return 0;
27. }

Output of program:

Fibonacci series C program using recursion


1. #include<stdio.h>
2.
3. int f(int);
4.
5. int main()
6. {
7. int n, i = 0, c;
8.
9. scanf("%d", &n);
10.
11. printf("Fibonacci series terms are:\n");
12.
13. for (c = 1; c <= n; c++)
14. {
15. printf("%d\n", f(i));
16. i++;
17. }
18.
19. return 0;
20. }
21.
22. int f(int n)
23. {
24. if (n == 0 || n == 1)
25. return n;
26. else
27. return (f(n-1) + f(n-2));
28. }

The recursive method is less efficient as it involves repeated function calls


and there are chances of stack overflow as the function will frequently be
called for calculating larger Fibonacci numbers. This sequence has many
applications in Mathematics and Computer Science.

Pascal triangle in C
1. #include <stdio.h>
2.
3. long factorial(int);
4.
5. int main()
6. {
7. int i, n, c;
8.
9. printf("Enter the number of rows you wish to see in
pascal triangle\n");
10. scanf("%d",&n);
11.
12. for (i = 0; i < n; i++)
13. {
14. for (c = 0; c <= (n - i - 2); c++)
15. printf(" ");
16.
17. for (c = 0 ; c <= i; c++)
18. printf("%ld
",factorial(i)/(factorial(c)*factorial(i-c)));
19.
20. printf("\n");
21. }
22.
23. return 0;
24. }
25.
26. long factorial(int n)
27. {
28. int c;
29. long result = 1;
30.
31. for (c = 1; c <= n; c++)
32. result = result*c;
33.
34. return result;
35. }

Pascal triangle C program output:

Download Pascal triangle program.

For more patterns or shapes on numbers and characters see codes on


following pages:
Patterns programs
Floyd triangle
C program to print Floyd's triangle
C program to print Floyd's triangle: A user will input how many numbers of
rows of Floyd's triangle to print. First four rows of Floyd's triangle are:
1
23
456
7 8 9 10
It's clear that in Floyd's triangle, nth row contains n numbers.

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. int n, i, c, a = 1;
6.
7. printf("Enter the number of rows of Floyd's triangle
to print\n");
8. scanf("%d", &n);
9.
10. for (i = 1; i <= n; i++)
11. {
12. for (c = 1; c <= i; c++)
13. {
14. printf("%d ",a);
15. a++;
16. }
17. printf("\n");
18. }
19.
20. return 0;
21. }
Output of program:

Download Floyd triangle program.

C program to print Floyd's triangle using


recursion
1. #include <stdio.h>
2.
3. void print_floyd(int);
4.
5. int main()
6. {
7. int n, i, c, a = 1;
8.
9. printf("Input number of rows of Floyd's triangle to
print\n");
10. scanf("%d", &n);
11.
12. print_floyd(n);
13.
14. return 0;
15. }
16.
17. void print_floyd(int n) {
18. static int row = 1, c = 1;
19. int d;
20.
21. if (n <= 0)
22. return;
23.
24. for (d = 1; d <= row; ++d)
25. printf("%d ", c++);
26.
27. printf("\n");
28. row++;
29.
30. print_floyd(--n);
31. }

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. int first, second, *p, *q, sum;
6.
7. printf("Enter two integers to add\n");
8. scanf("%d%d", &first, &second);
9.
10. p = &first;
11. q = &second;
12.
13. sum = *p + *q;
14.
15. printf("Sum of the numbers = %d\n", sum);
16.
17. return 0;
18. }

Download Add integers using pointers program.

Output of program:
C program to add numbers using call by reference
1. #include <stdio.h>
2.
3. long add(long *, long *);
4.
5. int main()
6. {
7. long first, second, *p, *q, sum;
8.
9. printf("Input two integers to add\n");
10. scanf("%ld%ld", &first, &second);
11.
12. sum = add(&first, &second);
13.
14. printf("(%ld) + (%ld) =
(%ld)\n", first, second, sum);
15.
16. return 0;
17. }
18.
19. long add(long *x, long *y) {
20. long sum;
21.
22. sum = *x + *y;
23.
24. return sum;
25. }

Linear search in C
Linear search in C programming: The following code implements linear
search (Searching algorithm) which is used to find whether a given number
is present in an array and if it is present then at what location it occurs. It is
also known as sequential search. It is straightforward and works as follows:
We keep on comparing each element with the element to search until it is
found or the list ends. Linear search in C language for multiple
occurrences and using function.

Linear search C program


1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], search, c, n;
6.
7. printf("Enter number of elements in array\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d integer(s)\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. printf("Enter a number to search\n");
16. scanf("%d", &search);
17.
18. for (c = 0; c < n; c++)
19. {
20. if (array[c] == search) /* If required
element is found */
21. {
22. printf("%d is present at location
%d.\n", search, c+1);
23. break;
24. }
25. }
26. if (c == n)
27. printf("%d isn't present in the
array.\n", search);
28.
29. return 0;
30. }
Output of program:

Download Linear search program.

C program for binary search

Linear search for multiple occurrences


In the code below we will print all the locations at which required element
is found and also the number of times it occur in the list.

1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], search, c, n, count = 0;
6.
7. printf("Enter number of elements in array\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d numbers\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. printf("Enter a number to search\n");
16. scanf("%d", &search);
17.
18. for (c = 0; c < n; c++) {
19. if (array[c] == search) {
20. printf("%d is present at location
%d.\n", search, c+1);
21. count++;
22. }
23. }
24. if (count == 0)
25. printf("%d isn't present in the
array.\n", search);
26. else
27. printf("%d is present %d times in the
array.\n", search, count);
28.
29. return 0;
30. }

Download Linear search multiple occurrence program.

Output of code:

C program for linear search using function


1. #include <stdio.h>
2.
3. long linear_search(long [], long, long);
4.
5. int main()
6. {
7. long array[100], search, c, n, position;
8.
9. printf("Input number of elements in array\n");
10. scanf("%ld", &n);
11.
12. printf("Input %d numbers\n", n);
13.
14. for (c = 0; c < n; c++)
15. scanf("%ld", &array[c]);
16.
17. printf("Input a number to search\n");
18. scanf("%ld", &search);
19.
20. position = linear_search(array, n, search);
21.
22. if (position == -1)
23. printf("%d isn't present in the
array.\n", search);
24. else
25. printf("%d is present at location
%d.\n", search, position+1);
26.
27. return 0;
28. }
29.
30. long linear_search(long a[], long n, long find) {
31. long c;
32.
33. for (c = 0 ;c < n ; c++ ) {
34. if (a[c] == find)
35. return c;
36. }
37.
38. return -1;
39. }

Linear search function using pointers


1. long linear_search(long *pointer, long n, long find)
2. {
3. long c;
4.
5. for (c = 0; c < n; c++) {
6. if (*(pointer+c) == find)
7. return c;
8. }
9.
10. return -1;
11. }

Time required to search an element using linear search algorithm depends


on size of the list. In the best case it is present at the beginning of the list
and in the worst case element is present at the end. The time complexity of
linear search is O(n).

C program for binary search


C program for binary search: This code implements binary search in C
language. It can only be used for sorted arrays, but it's fast as compared to
linear search. If you wish to use binary search on an array which isn't
sorted, then you must sort it using some sorting technique say merge sort
and then use the binary search algorithm to find the desired element in the
list. If the element to be searched is found then its position is printed. The
code below assumes that the input numbers are in ascending order.

C programming code for binary search


1. #include <stdio.h>
2.
3. int main()
4. {
5. int c, first, last, middle, n, search, array[100];
6.
7. printf("Enter number of elements\n");
8. scanf("%d",&n);
9.
10. printf("Enter %d integers\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d",&array[c]);
14.
15. printf("Enter value to find\n");
16. scanf("%d", &search);
17.
18. first = 0;
19. last = n - 1;
20. middle = (first+last)/2;
21.
22. while (first <= last) {
23. if (array[middle] < search)
24. first = middle + 1;
25. else if (array[middle] == search) {
26. printf("%d found at location
%d.\n", search, middle+1);
27. break;
28. }
29. else
30. last = middle - 1;
31.
32. middle = (first + last)/2;
33. }
34. if (first > last)
35. printf("Not found! %d isn't present in the
list.\n", search);
36.
37. return 0;
38. }
Output of program:

C program for linear search

Download Binary search program.

Binary search is faster than linear search, but the list should be sorted,
hashing is more rapid than binary search and perform searches in constant
time.

program to insert an element in an array


C program to insert an element in an array, for example, consider an array
a[10] having three elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3
and you want to insert a number 45 at location 1 i.e. a[0] = 45, so we have
to move elements one step below so after insertion a[1] = 1 which was a[0]
initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean
increasing its size i.e array will not contain 11 elements.

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], position, c, n, value;
6.
7. printf("Enter number of elements in array\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d elements\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. printf("Enter the location where you wish to
insert an element\n");
16. scanf("%d", &position);
17.
18. printf("Enter the value to insert\n");
19. scanf("%d", &value);
20.
21. for (c = n - 1; c >= position - 1; c--)
22. array[c+1] = array[c];
23.
24. array[position-1] = value;
25.
26. printf("Resultant array is\n");
27.
28. for (c = 0; c <= n; c++)
29. printf("%d\n", array[c]);
30.
31. return 0;
32. }
Output of program:

Download Insert element in array program.

C program to delete an element from an array


C program to delete an element in an array: This program deletes or
removes an element from an array. A user will enter the position at which
the array element deletion is required. Deleting an element does not affect
the size of the array. It also checks whether deletion is possible or not, for
example, if an array contains five elements and user wants to delete the
element at the sixth position, it isn't possible.

Remove element from array C program


1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], position, c, n;
6.
7. printf("Enter number of elements in array\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d elements\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. printf("Enter the location where you wish to
delete element\n");
16. scanf("%d", &position);
17.
18. if (position >= n+1)
19. printf("Deletion not possible.\n");
20. else
21. {
22. for (c = position - 1; c < n - 1; c++)
23. array[c] = array[c+1];
24.
25. printf("Resultant array:\n");
26.
27. for (c = 0; c < n - 1; c++)
28. printf("%d\n", array[c]);
29. }
30.
31. return 0;
32. }

C program to delete element from array output:

Download Delete element from array program.


You may have observed that we need to shift array elements which are after
the element to be deleted, it is very inefficient if the size of the array is large
or we need to remove elements from an array repeatedly. In linked list data
structure shifting isn't required only pointers are adjusted. If frequent
deletion is required and the number of elements is large, it is recommended
to use a linked list.

Bubble sort algorithm implementation in C


1. /* Bubble sort code */
2.
3. #include <stdio.h>
4.
5. int main()
6. {
7. int array[100], n, c, d, swap;
8.
9. printf("Enter number of elements\n");
10. scanf("%d", &n);
11.
12. printf("Enter %d integers\n", n);
13.
14. for (c = 0; c < n; c++)
15. scanf("%d", &array[c]);
16.
17. for (c = 0 ; c < n - 1; c++)
18. {
19. for (d = 0 ; d < n - c - 1; d++)
20. {
21. if (array[d] > array[d+1]) /* For decreasing
order use < */
22. {
23. swap = array[d];
24. array[d] = array[d+1];
25. array[d+1] = swap;
26. }
27. }
28. }
29.
30. printf("Sorted list in ascending order:\n");
31.
32. for (c = 0; c < n; c++)
33. printf("%d\n", array[c]);
34.
35. return 0;
36. }

Output of program:

Download Bubble sort program.

Bubble sort in C language using function


1. #include <stdio.h>
2.
3. void bubble_sort(long [], long);
4.
5. int main()
6. {
7. long array[100], n, c, d, swap;
8.
9. printf("Enter number of elements\n");
10. scanf("%ld", &n);
11.
12. printf("Enter %ld integers\n", n);
13.
14. for (c = 0; c < n; c++)
15. scanf("%ld", &array[c]);
16.
17. bubble_sort(array, n);
18.
19. printf("Sorted list in ascending order:\n");
20.
21. for (c = 0; c < n; c++)
22. printf("%ld\n", array[c]);
23.
24. return 0;
25. }
26.
27. void bubble_sort(long list[], long n)
28. {
29. long c, d, t;
30.
31. for (c = 0 ; c < n - 1; c++)
32. {
33. for (d = 0 ; d < n - c - 1; d++)
34. {
35. if (list[d] > list[d+1])
36. {
37. /* Swapping */
38.
39. t = list[d];
40. list[d] = list[d+1];
41. list[d+1] = t;
42. }
43. }
44. }
45. }

Insertion sort algorithm implementation in C


1. /* Insertion sort ascending order */
2.
3. #include <stdio.h>
4.
5. int main()
6. {
7. int n, array[1000], c, d, t;
8.
9. printf("Enter number of elements\n");
10. scanf("%d", &n);
11.
12. printf("Enter %d integers\n", n);
13.
14. for (c = 0; c < n; c++)
15. scanf("%d", &array[c]);
16.
17. for (c = 1 ; c <= n - 1; c++) {
18. d = c;
19.
20. while ( d > 0 && array[d-1] > array[d]) {
21. t = array[d];
22. array[d] = array[d-1];
23. array[d-1] = t;
24.
25. d--;
26. }
27. }
28.
29. printf("Sorted list in ascending order:\n");
30.
31. for (c = 0; c <= n - 1; c++) {
32. printf("%d\n", array[c]);
33. }
34.
35. return 0;
36. }
Output of program:

Download Insertion sort program.

Best case complexity of insertion sort is O(n), average and the worst case
complexity is O(n2).

Selection sort in C
Selection sort in C: C program for selection sort to sort numbers. This code
implements selection sort algorithm to arrange numbers of an array in
ascending order. With a little modification, it will arrange numbers in
descending order.

Selection sort algorithm implementation in C


1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], n, c, d, position, swap;
6.
7. printf("Enter number of elements\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d integers\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. for (c = 0; c < (n - 1); c++)
16. {
17. position = c;
18.
19. for (d = c + 1; d < n; d++)
20. {
21. if (array[position] > array[d])
22. position = d;
23. }
24. if (position != c)
25. {
26. swap = array[c];
27. array[c] = array[position];
28. array[position] = swap;
29. }
30. }
31.
32. printf("Sorted list in ascending order:\n");
33.
34. for (c = 0; c < n; c++)
35. printf("%d\n", array[c]);
36.
37. return 0;
38. }
Output of program:

Download Selection sort program.

Matrix addition in C
Matrix addition in C: C program to add two matrices, i.e., compute the sum
of two matrices and then print it. Firstly a user will be asked to enter the
order of matrix (number of rows and columns) and then two matrices. For
example, if a user input order as 2, 2, i.e., two rows and two columns and
matrices as
First matrix:
12
34
Second matrix:
45
-1 5
then the output of the program (Summation of the two matrices) is:
57
29
Matrices are frequently used in programming to represent graph data
structure, in solving equations and in many other ways.

Addition of two matrix in C


C program for matrix addition:

1. #include <stdio.h>
2.
3. int main()
4. {
5. int m, n, c, d, first[10][10], second[10][10], sum[1
0][10];
6.
7. printf("Enter the number of rows and columns of
matrix\n");
8. scanf("%d%d", &m, &n);
9. printf("Enter the elements of first matrix\n");
10.
11. for (c = 0; c < m; c++)
12. for (d = 0; d < n; d++)
13. scanf("%d", &first[c][d]);
14.
15. printf("Enter the elements of second matrix\n");
16.
17. for (c = 0; c < m; c++)
18. for (d = 0 ; d < n; d++)
19. scanf("%d", &second[c][d]);
20.
21. printf("Sum of entered matrices:-\n");
22.
23. for (c = 0; c < m; c++) {
24. for (d = 0 ; d < n; d++) {
25. sum[c][d] = first[c][d] + second[c][d];
26. printf("%d\t", sum[c][d]);
27. }
28. printf("\n");
29. }
30.
31. return 0;
32. }
Output of matrix addition C program:

Download Add Matrix program.

Similarly, we can create a program to subtract two matrices. You can also
create a function to perform addition of two matrices.

Transpose of a matrix in C
Transpose of a matrix in C language: This C program prints transpose of a
matrix. It is obtained by interchanging rows and columns of a matrix. For
example, consider the following 3 X 2 matrix:
12
34
56
Transpose of the matrix:
135
246
When we transpose a matrix then its order changes, but for a square matrix
it remains the same.

C program to find transpose of a matrix


1. #include <stdio.h>
2.
3. int main()
4. {
5. int m, n, c, d, matrix[10][10], transpose[10][10];
6.
7. printf("Enter the number of rows and columns of
matrix\n");
8. scanf("%d%d", &m, &n);
9.
10. printf("Enter elements of the matrix\n");
11.
12. for (c = 0; c < m; c++)
13. for(d = 0; d < n; d++)
14. scanf("%d", &matrix[c][d]);
15.
16. for (c = 0; c < m; c++)
17. for( d = 0 ; d < n ; d++ )
18. transpose[d][c] = matrix[c][d];
19.
20. printf("Transpose of the matrix:\n");
21.
22. for (c = 0; c < n; c++) {
23. for (d = 0; d < m; d++)
24. printf("%d\t", transpose[c][d]);
25. printf("\n");
26. }
27.
28. return 0;
29. }

Output of program:

Download Transpose Matrix program.


Matrix multiplication in C
Matrix multiplication in C language: C program to multiply two matrices
(two-dimensional arrays) which will be entered by a user. The user will
enter the order of a matrix and then its elements and similarly inputs the
second matrix. If the orders of the matrices are such that they can't be
multiplied by each other, then an error message is displayed. You may have
studied the method to multiply matrices in Mathematics.

Matrix multiplication in C language


1. #include <stdio.h>
2.
3. int main()
4. {
5. int m, n, p, q, c, d, k, sum = 0;
6. int first[10][10], second[10][10], multiply[10][10];
7.
8. printf("Enter number of rows and columns of first
matrix\n");
9. scanf("%d%d", &m, &n);
10. printf("Enter elements of first matrix\n");
11.
12. for (c = 0; c < m; c++)
13. for (d = 0; d < n; d++)
14. scanf("%d", &first[c][d]);
15.
16. printf("Enter number of rows and columns of
second matrix\n");
17. scanf("%d%d", &p, &q);
18.
19. if (n != p)
20. printf("The matrices can't be multiplied with
each other.\n");
21. else
22. {
23. printf("Enter elements of second matrix\n");
24.
25. for (c = 0; c < p; c++)
26. for (d = 0; d < q; d++)
27. scanf("%d", &second[c][d]);
28.
29. for (c = 0; c < m; c++) {
30. for (d = 0; d < q; d++) {
31. for (k = 0; k < p; k++) {
32. sum = sum + first[c][k]*second[k][d];
33. }
34.
35. multiply[c][d] = sum;
36. sum = 0;
37. }
38. }
39.
40. printf("Product of the matrices:\n");
41.
42. for (c = 0; c < m; c++) {
43. for (d = 0; d < q; d++)
44. printf("%d\t", multiply[c][d]);
45.
46. printf("\n");
47. }
48. }
49.
50. return 0;
51. }

An output of 3 X 3 matrix multiplication C program:


Download Matrix multiplication program.

Matrices are frequently used in programming and are used to represent


graph data structure, in solving a system of linear equations and have many
other applications. A lot of research is being done on how to multiply
matrices using a minimum number of operations. You can also implement
this program using pointers.

String length C program


1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char a[100];
7. int length;
8.
9. printf("Enter a string to calculate it's length\n");
10. gets(a);
11.
12. length = strlen(a);
13.
14. printf("Length of the string = %d\n", length);
15.
16. return 0;
17. }

Download String length program.

Output of program:

String length in C without strlen


You can also find string length without strlen function. We create our
function to find it. We scan all the characters in the string if the character
isn't a null character then increment the counter by one. Once the null
character is found the counter equals length of the string.

1. #include <stdio.h>
2.
3. int main()
4. {
5. char s[1000];
6. int c = 0;
7.
8. printf("Input a string\n");
9. gets(s);
10.
11. while (s[c] != '\0')
12. c++;
13.
14. printf("Length of the string: %d\n", c);
15.
16. return 0;
17. }

Function to find string length:

1. int string_length(char s[]) {


2. int c = 0;
3.
4. while (s[c] != '\0')
5. c++;
6.
7. return c;
8. }

C program to find length of a string using recursion

1. #include <stdio.h>
2.
3. int string_length(char*);
4.
5. int main()
6. {
7. char s[100];
8.
9. gets(s);
10.
11. printf("Length = %d\n", string_length(s));
12.
13. return 0;
14. }
15.
16. int string_length(char *s) {
17. static int c = 0;
18.
19. while (s[c] != '\0') {
20. c++;
21. string_length(s+1);
22. }
23.
24. return c;
25. }

Function to find string length using pointers

1. int string_length(char *s) {


2. int c = 0;
3.
4. while(*s[c] != '\0')
5. c++;
6.
7. return c;
8. }

C program to compare two strings


C program to compare two strings using strcmp function, without strcmp
function and using pointers. Function strcmp is case sensitive and returns 0
if both the strings are same.

String comparison C program


1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char a[100], b[100];
7.
8. printf("Enter a string\n");
9. gets(a);
10.
11. printf("Enter a string\n");
12. gets(b);
13.
14. if (strcmp(a,b) == 0)
15. printf("The strings are equal.\n");
16. else
17. printf("The strings are not equal.\n");
18.
19. return 0;
20. }
Output of program:

Download Compare Strings program.

C string comparison program


We can create a function to compare two strings.

1. #include <stdio.h>
2.
3. int compare_strings(char [], char []);
4.
5. int main()
6. {
7. char a[1000], b[1000];
8.
9. printf("Input a string\n");
10. gets(a);
11.
12. printf("Input a string\n");
13. gets(b);
14.
15. if (compare_strings(a, b) == 0)
16. printf("Equal strings.\n");
17. else
18. printf("Unequal strings.\n");
19.
20. return 0;
21. }
22.
23. int compare_strings(char a[], char b[])
24. {
25. int c = 0;
26.
27. while (a[c] == b[c]) {
28. if (a[c] == '\0' || b[c] == '\0')
29. break;
30. c++;
31. }
32.
33. if (a[c] == '\0' && b[c] == '\0')
34. return 0;
35. else
36. return -1;
37. }

C program to compare two strings using


pointers
We can make a function to check if two strings are similar or not by using
character pointers.

1. #include<stdio.h>
2.
3. int compare_string(char*, char*);
4.
5. int main()
6. {
7. char first[1000], second[1000]:
8. int result;
9.
10. printf("Input a string\n");
11. gets(first);
12.
13. printf("Input a string\n");
14. gets(second);
15.
16. result = compare_string(first, second);
17.
18. if (result == 0)
19. printf("The strings are same.\n");
20. else
21. printf("The strings are different.\n");
22.
23. return 0;
24. }
25.
26. int compare_string(char *first, char *second) {
27. while (*first == *second) {
28. if (*first == '\0' || *second == '\0')
29. break;
30.
31. first++;
32. second++;
33. }
34.
35. if (*first == '\0' && *second == '\0')
36. return 0;
37. else
38. return -1;
39. }

String comparison is a part of pattern matching e.g. when you


press Ctrl+F in a web browser or text editor to search for some text.

C program to reverse a string


Reverse a string in C: This program reverses a string that a user inputs. For
example, if a user enters a string "hello" then on reversing it will be "olleh".
C program to reverse a string using strrev, without using
strrev, recursion and pointers. A string which remains the same on reversal
is a palindrome string.

Reverse a string in C using strrev


1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char arr[100];
7.
8. printf("Enter a string to reverse\n");
9. gets(arr);
10.
11. strrev(arr);
12.
13. printf("Reverse of the string is \n%s\n", arr);
14.
15. return 0;
16. }

C reverse string program output:

Download Reverse string program.

C program to reverse words in a string

String reversal without strrev function


First we calculate length of the string without using strlen function and
then copy its characters in reverse order (from end to beginning) to a new
string using a for loop.

1. #include <stdio.h>
2.
3. int main()
4. {
5. char s[1000], r[1000];
6. int begin, end, count = 0;
7.
8. printf("Input a string\n");
9. gets(s);
10.
11. // Calculating string length
12.
13. while (s[count] != '\0')
14. count++;
15.
16. end = count - 1;
17.
18. for (begin = 0; begin < count; begin++) {
19. r[begin] = s[end];
20. end--;
21. }
22.
23. r[begin] = '\0';
24.
25. printf("%s\n", r);
26.
27. return 0;
28. }

C program to reverse a string using recursion


1. #include <stdio.h>
2. #include <string.h>
3.
4. void reverse(char*, int, int);
5.
6. int main()
7. {
8. char a[100];
9.
10. gets(a);
11.
12. reverse(a, 0, strlen(a)-1);
13.
14. printf("%s\n", a);
15.
16. return 0;
17. }
18.
19. void reverse(char *x, int begin, int end)
20. {
21. char c;
22.
23. if (begin >= end)
24. return;
25.
26. c = *(x+begin);
27. *(x+begin) = *(x+end);
28. *(x+end) = c;
29.
30. reverse(x, ++begin, --end);
31. }

In the recursive method, we swap characters at the beginning and the end
of the string and then move towards the middle of the string. This way is
inefficient due to repeated function calls but useful in practicing recursion.

C program to reverse a string using pointers


Now we will invert a string using pointers or without using the library
function strrev.

1. #include<stdio.h>
2.
3. int string_length(char*);
4. void reverse(char*);
5.
6. main()
7. {
8. char s[100];
9.
10. printf("Enter a string\n");
11. gets(s);
12.
13. reverse(s);
14.
15. printf("Reverse of the string is \"%s\".\n", s);
16.
17. return 0;
18. }
19.
20. void reverse(char *s)
21. {
22. int length, c;
23. char *begin, *end, temp;
24.
25. length = string_length(s);
26. begin = s;
27. end = s;
28.
29. for (c = 0; c < length - 1; c++)
30. end++;
31.
32. for (c = 0; c < length/2; c++)
33. {
34. temp = *end;
35. *end = *begin;
36. *begin = temp;
37.
38. begin++;
39. end--;
40. }
41. }
42.
43. int string_length(char *pointer)
44. {
45. int c = 0;
46.
47. while( *(pointer + c) != '\0' )
48. c++;
49.
50. return c;
51. }

C substring, substring in C
C substring: C program to find substring of a string and all substrings of a
string. A substring is itself a string that is part of a longer string. For
example, substrings of string "the" are "" (empty string), "t", "th", "the", "h",
"he" and "e". Header file "string.h" does not contain any library function to
find a substring directly.

C substring program
1. #include <stdio.h>
2.
3. int main()
4. {
5. char string[1000], sub[1000];
6. int position, length, c = 0;
7.
8. printf("Input a string\n");
9. gets(string);
10.
11. printf("Enter the position and length of
substring\n");
12. scanf("%d%d", &position, &length);
13.
14. while (c < length) {
15. sub[c] = string[position+c-1];
16. c++;
17. }
18. sub[c] = '\0';
19.
20. printf("Required substring is \"%s\"\n", sub);
21.
22. return 0;
23. }

C substring program output:

Substring in C language using function


We create a function and pass it four arguments original string array,
substring array, position and length of the required substring. As we use
call by reference, we do not need to return substring array. See another
code below in which we return a pointer to substring, which we create in
our array using dynamic memory allocation.

1. #include <stdio.h>
2.
3. void substring(char [], char[], int, int);
4.
5. int main()
6. {
7. char string[1000], sub[1000];
8. int position, length, c = 0;
9.
10. printf("Input a string\n");
11. gets(string);
12.
13. printf("Enter the position and length of
substring\n");
14. scanf("%d%d", &position, &length);
15.
16. substring(string, sub, position, length);
17.
18. printf("Required substring is \"%s\"\n", sub);
19.
20. return 0;
21. }
22. //C substring function definition
23. void substring(char s[], char sub[], int p, int l)
{
24. int c = 0;
25.
26. while (c < l) {
27. sub[c] = s[p+c-1];
28. c++;
29. }
30. sub[c] = '\0';
31. }

C substring program using pointers


To find substring we create a substring function which returns a pointer to
string. String address, required length of substring and position from where
to extract substring are the three arguments passed to function.

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. char* substring(char*, int, int);
5.
6. int main()
7. {
8. char string[100], *pointer;
9. int position, length;
10.
11. printf("Input a string\n");
12. gets(string);
13.
14. printf("Enter the position and length of
substring\n");
15. scanf("%d%d",&position, &length);
16.
17. pointer = substring( string, position, length);
18.
19. printf("Required substring
is \"%s\"\n", pointer);
20.
21. free(pointer);
22.
23. return 0;
24. }
25.
26. /*C substring function: It returns a pointer to the
substring */
27.
28. char *substring(char *string, int position, int len
gth)
29. {
30. char *pointer;
31. int c;
32.
33. pointer = malloc(length+1);
34.
35. if (pointer == NULL)
36. {
37. printf("Unable to allocate memory.\n");
38. exit(1);
39. }
40.
41. for (c = 0 ; c < length ; c++)
42. {
43. *(pointer+c) = *(string+position-1);
44. string++;
45. }
46.
47. *(pointer+c) = '\0';
48.
49. return pointer;
50. }

C program for all substrings of a string


1. #include <stdio.h>
2. #include <string.h>
3. #include <malloc.h>
4.
5. char* substring(char*, int, int);
6.
7. int main()
8. {
9. char string[100], *pointer;
10. int position = 1, length = 1, temp, string_lengt
h;
11.
12. printf("Enter a string\n");
13. gets(string);
14.
15. temp = string_length = strlen(string);
16.
17. printf("Substring of \"%s\" are\n", string);
18.
19. while (position <= string_length)
20. {
21. while (length <= temp)
22. {
23. pointer = substring(string, position, leng
th);
24. printf("%s\n", pointer);
25. free(pointer);
26. length++;
27. }
28. temp--;
29. position++;
30. length = 1;
31. }
32.
33. return 0;
34. }
35.
36. /* Use substring function given in above C
program*/

Substring program output:

C program to check subsequence


C program to check Subsequence, don't confuse subsequence with
substring. In our program, we check if a string is a subsequence of another
string. A user will input two strings, and we find if one of the strings is a
subsequence of the other. Program prints yes if either the first string is a
subsequence of the second string or the second string is a subsequence of
the first string. We pass smaller length string first because our function
assumes the first string is of smaller or equal length than the second string.

C programming code
1. #include <stdio.h>
2. #include <string.h>
3.
4. int check_subsequence (char [], char[]);
5.
6. int main () {
7. int flag;
8. char s1[1000], s2[1000];
9.
10. printf("Input first string\n");
11. gets(s1);
12.
13. printf("Input second string\n");
14. gets(s2);
15.
16. /** Passing smaller length string first */
17.
18. if (strlen(s1) < strlen(s2))
19. flag = check_subsequence(s1, s2);
20. else
21. flag = check_subsequence(s2, s1);
22.
23. if (flag)
24. printf("YES\n");
25. else
26. printf("NO\n");
27.
28. return 0;
29. }
30.
31. int check_subsequence (char a[], char b[]) {
32. int c, d;
33.
34. c = d = 0;
35.
36. while (a[c] != '\0') {
37. while ((a[c] != b[d]) && b[d] != '\0') {
38. d++;
39. }
40. if (b[d] == '\0')
41. break;
42. d++;
43. c++;
44. }
45. if (a[c] == '\0')
46. return 1;
47. else
48. return 0;
49. }

An output of the program:

1. Input first string


2. tree
3. Input second string
4. Computer science is awesome
5. YES

Logic of the function is simple; we keep on comparing characters of two


strings, if a mismatch occurs then we move to the next character of the
second string and if characters match, indexes of both the strings are
increased by one and so on. If the first string ends then it is a subsequence
otherwise not.

C program remove spaces, blanks from a string


C program 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 the string
"C programming." It will remove spaces when they occur more than one
time consecutively in string anywhere.

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. char text[1000], blank[1000];
6. int c = 0, d = 0;
7.
8. printf("Enter some text\n");
9. gets(text);
10.
11. while (text[c] != '\0') {
12. if (text[c] == ' ') {
13. int temp = c + 1;
14. if (text[temp] != '\0') {
15. while (text[temp] == '
' && text[temp] != '\0') {
16. if (text[temp] == ' ') {
17. c++;
18. }
19. temp++;
20. }
21. }
22. }
23. blank[d] = text[c];
24. c++;
25. d++;
26. }
27.
28. blank[d] = '\0';
29.
30. printf("Text after removing
blanks\n%s\n", blank);
31.
32. return 0;
33. }

If you want you can copy blank into text string so that original string is
modified.

Download Remove spaces program.


Output of program:

C programming code using pointers


1. #include <stdio.h>
2. #include <string.h>
3. #include <stdlib.h>
4. #define SPACE ' '
5.
6. char *process(char*);
7.
8. int main()
9. {
10. char text[1000], *r;
11.
12. printf("Enter a string\n");
13. gets(text);
14.
15. r = process(text);
16.
17. printf("\"%s\"\n", r);
18.
19. free(r);
20.
21. return 0;
22. }
23.
24. char *process(char *text) {
25. int length, c, d;
26. char *start;
27.
28. c = d = 0;
29.
30. length = strlen(text);
31.
32. start = (char*)malloc(length+1);
33.
34. if (start == NULL)
35. exit(EXIT_FAILURE);
36.
37. while (*(text+c) != '\0') {
38. if (*(text+c) == ' ') {
39. int temp = c + 1;
40. if (*(text+temp) != '\0') {
41. while (*(text+temp) == '
' && *(text+temp) != '\0') {
42. if (*(text+temp) == ' ') {
43. c++;
44. }
45. temp++;
46. }
47. }
48. }
49. *(start+d) = *(text+c);
50. c++;
51. d++;
52. }
53. *(start+d)= '\0';
54.
55. return start;
56. }

C program to change case of a string


Strlwr function converts a string to lower case, and strupr function converts
a string to upper case. Here we will change string case with and without
strlwr, strupr functions. These functions convert case of alphabets and
ignore other characters which may be present in a string.

Function strlwr in C
1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char string[1000];
7.
8. printf("Input a string to convert to lower case\n");
9. gets(string);
10.
11. printf("The string in lower case:
%s\n", strlwr(string));
12.
13. return 0;
14. }

Function strupr in C
1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char string[1000];
7.
8. printf("Input a string to convert to upper case\n");
9. gets(string);
10.
11. printf("The string in upper case:
%s\n", strupr(string));
12.
13. return 0;
14. }

Change string to upper case without strupr


1. #include <stdio.h>
2.
3. void upper_string(char []);
4.
5. int main()
6. {
7. char string[100];
8.
9. printf("Enter a string to convert it into upper
case\n");
10. gets(string);
11.
12. upper_string(string);
13.
14. printf("The string in upper case:
%s\n", string);
15.
16. return 0;
17. }
18.
19. void upper_string(char s[]) {
20. int c = 0;
21.
22. while (s[c] != '\0') {
23. if (s[c] >= 'a' && s[c] <= 'z') {
24. s[c] = s[c] - 32;
25. }
26. c++;
27. }
28. }

Change string to lower case without strlwr


1. #include <stdio.h>
2.
3. void lower_string(char []);
4.
5. int main()
6. {
7. char string[100];
8.
9. printf("Enter a string to convert it into lower
case\n");
10. gets(string);
11.
12. lower_string(string);
13.
14. printf("The string in lower case:
%s\n", string);
15.
16. return 0;
17. }
18.
19. void lower_string(char s[]) {
20. int c = 0;
21.
22. while (s[c] != '\0') {
23. if (s[c] >= 'A' && s[c] <= 'Z') {
24. s[c] = s[c] + 32;
25. }
26. c++;
27. }
28. }

You can also implement functions using pointers.

C program to change case from upper to


lower and lower to upper
Below program changes case of alphabets if a lower case alphabet is found
it is converted to upper and if an upper case is found it is converted to lower
case.

1. #include <stdio.h>
2.
3. int main ()
4. {
5. int c = 0;
6. char ch, s[1000];
7.
8. printf("Input a string\n");
9. gets(s);
10.
11. while (s[c] != '\0') {
12. ch = s[c];
13. if (ch >= 'A' && ch <= 'Z')
14. s[c] = s[c] + 32;
15. else if (ch >= 'a' && ch <= 'z')
16. s[c] = s[c] - 32;
17. c++;
18. }
19.
20. printf("%s\n", s);
21.
22. return 0;
23. }

An output of the program:

1. Input a string
2. abcdefghijklmnopqrstuvwxyz{0123456789}ABCDEFGHIJKLMNOPQ
RSTUVWXYZ
3. ABCDEFGHIJKLMNOPQRSTUVWXYZ{0123456789}abcdefghijklmnopq
rstuvwxyz

If a digit or special character is present in a string, it is left as it is.

C program to find the frequency of characters in a string


C program to find the frequency of characters in a string: This program
counts the frequency of characters in a string, i.e., which character is
present how many times in the string. For example, in the string "code"
each of the characters 'c,' 'd,' 'e,' and 'o' has occurred one time. Only lower
case alphabets are considered, other characters (uppercase and special
characters) are ignored. You can easily modify this program to handle
uppercase and special symbols.

C programming code
1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char string[100];
7. int c = 0, count[26] = {0}, x;
8.
9. printf("Enter a string\n");
10. gets(string);
11.
12. while (string[c] != '\0') {
13. /** Considering characters from 'a' to 'z' only
and ignoring others. */
14.
15. if (string[c] >= 'a' && string[c] <= 'z') {
16. x = string[c] - 'a';
17. count[x]++;
18. }
19.
20. c++;
21. }
22.
23. for (c = 0; c < 26; c++)
24. printf("%c occurs %d times in the
string.\n", c + 'a', count[c]);
25.
26. return 0;
27. }

Explanation of "count[string[c]-'a']++", suppose input string begins with 'a'


so c is 0 initially and string[0] = 'a' and string[0] - 'a' = 0 and we increment
count[0] i.e. 'a' has occurred one time and repeat this till the complete
string is scanned.

Download Character frequency program.


Output of program:

Did you notice that the string in the output of the program contains every
alphabet at least once?

Calculating frequency using function


We will make a function which computes frequency of characters in input
string and print it in a table (see output image below).

1. #include <stdio.h>
2. #include <string.h>
3.
4. void find_frequency(char [], int []);
5.
6. int main()
7. {
8. char string[100];
9. int c, count[26] = {0};
10.
11. printf("Input a string\n");
12. gets(string);
13.
14. find_frequency(string, count);
15.
16. printf("Character Count\n");
17.
18. for (c = 0 ; c < 26 ; c++)
19. printf("%c \t %d\n", c + 'a', count[c]);
20.
21. return 0;
22. }
23.
24. void find_frequency(char s[], int count[]) {
25. int c = 0;
26.
27. while (s[c] != '\0') {
28. if (s[c] >= 'a' && s[c] <= 'z' )
29. count[s[c]-'a']++;
30. c++;
31. }
32. }
Output of the program:

We do not pass no of elements of array count[] to function find_frequency


as they will always be 26 if considering only lower case alphabets. But you
can pass if you wish to do so.

Anagram program in C
Anagram program in C: C program to check whether two strings are
anagrams or not, a string is assumed to consist of lower case alphabets
only. Two words are said to be anagrams of each other if the letters of one
word can be rearranged to form the other word. So, in anagram strings, all
characters occur the same number of times. For example, "abc" and "cab"
are anagram strings, as every character 'a,' 'b,' and 'c' occur the same
number of times (one time here) in both the strings. A user will input two
strings, and our algorithm counts how many times each character ('a' to 'z')
appear in both the strings and then compare their corresponding counts.
The frequency of an alphabet in a string is how many times that alphabet
appears in the string. For example, the frequency of 'm' in the string
"programming" is '2' as it is present two times in "programming."
C anagram program
1. #include <stdio.h>
2.
3. int check_anagram(char [], char []);
4.
5. int main()
6. {
7. char a[100], b[100];
8.
9. printf("Enter a string\n");
10. gets(a);
11.
12. printf("Enter a string\n");
13. gets(b);
14.
15. if (check_anagram(a, b) == 1)
16. printf("The strings are anagrams.\n");
17. else
18. printf("The strings aren't anagrams.\n");
19.
20. return 0;
21. }
22.
23. int check_anagram(char a[], char b[])
24. {
25. int first[26] = {0}, second[26] = {0}, c=0;
26.
27. // Calculating frequency of characters of first
string
28.
29. while (a[c] != '\0')
30. {
31. first[a[c]-'a']++;
32. c++;
33. }
34.
35. c = 0;
36.
37. while (b[c] != '\0')
38. {
39. second[b[c]-'a']++;
40. c++;
41. }
42.
43. // Comparing frequency of characters
44.
45. for (c = 0; c < 26; c++)
46. {
47. if (first[c] != second[c])
48. return 0;
49. }
50.
51. return 1;
52. }

Output of C anagram program:

Download Anagram program.

C read file program


C read file program: This C language program reads a file whose name is
entered by a user and displays its contents on the screen. Function fopen is
used to open a file; it returns a pointer to structure FILE which is a
predefined structure in "stdio.h" header file. If the file is successfully
opened then fopen returns a pointer to the file and if it is unable to open the
file then it returns NULL. Function fgetc returns a character which is read
from the file, and fclose function closes the file. Opening a file means we
bring the file contents from disk to RAM to perform operations on it. The
file to be opened must be present in the directory in which the executable
file of this program is present.

File reading program in C


C programming code to open a file and print its contents on screen.

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. char ch, file_name[25];
7. FILE *fp;
8.
9. printf("Enter name of a file you wish to see\n");
10. gets(file_name);
11.
12. fp = fopen(file_name, "r"); // read mode
13.
14. if (fp == NULL)
15. {
16. perror("Error while opening the file.\n");
17. exit(EXIT_FAILURE);
18. }
19.
20. printf("The contents of %s file
are:\n", file_name);
21.
22. while((ch = fgetc(fp)) != EOF)
23. printf("%c", ch);
24.
25. fclose(fp);
26. return 0;
27. }

Read file C program output:


Download Read file program.

There are blank lines present at the end of the file. In our program we have
opened only one file, you can open multiple files in a single program and in
different modes as required. File handling is essential when we wish to
store data permanently on a storage device. All variables and data of a
program are lost when it exits if that data is required later we need to store
it in a file.

C program to copy a file


C program to copy a file: This program copies a file, firstly you will specify a
file to copy, and then you will enter name and extension of target file . We
will open the file that we wish to copy in "read" mode and target file in
"write" mode.

C programming code
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. char ch, source_file[20], target_file[20];
7. FILE *source, *target;
8.
9. printf("Enter name of file to copy\n");
10. gets(source_file);
11.
12. source = fopen(source_file, "r");
13.
14. if (source == NULL)
15. {
16. printf("Press any key to exit...\n");
17. exit(EXIT_FAILURE);
18. }
19.
20. printf("Enter name of target file\n");
21. gets(target_file);
22.
23. target = fopen(target_file, "w");
24.
25. if (target == NULL)
26. {
27. fclose(source);
28. printf("Press any key to exit...\n");
29. exit(EXIT_FAILURE);
30. }
31.
32. while ((ch = fgetc(source)) != EOF)
33. fputc(ch, target);
34.
35. printf("File copied successfully.\n");
36.
37. fclose(source);
38. fclose(target);
39.
40. return 0;
41. }

Download File copy program.

Output of program:

C program to merge two files


C program to merge two files and store 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 the merged file then we read the contents of another file and
store it in merged file, we read two files until EOF (end of file) is reached.

C programming code
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. FILE *fs1, *fs2, *ft;
7.
8. char ch, file1[20], file2[20], file3[20];
9.
10. printf("Enter name of first file\n");
11. gets(file1);
12.
13. printf("Enter name of second file\n");
14. gets(file2);
15.
16. printf("Enter name of file which will store
contents of the two files\n");
17. gets(file3);
18.
19. fs1 = fopen(file1, "r");
20. fs2 = fopen(file2, "r");
21.
22. if(fs1 == NULL || fs2 == NULL)
23. {
24. perror("Error ");
25. printf("Press any key to exit...\n");
26. exit(EXIT_FAILURE);
27. }
28.
29. ft = fopen(file3, "w"); // Opening in write mode
30.
31. if(ft == NULL)
32. {
33. perror("Error ");
34. printf("Press any key to exit...\n");
35. exit(EXIT_FAILURE);
36. }
37.
38. while((ch = fgetc(fs1)) != EOF)
39. fputc(ch,ft);
40.
41. while((ch = fgetc(fs2)) != EOF)
42. fputc(ch,ft);
43.
44. printf("The two files were merged into %s file
successfully.\n", file3);
45.
46. fclose(fs1);
47. fclose(fs2);
48. fclose(ft);
49.
50. return 0;
51. }

Download merge files program.

Output of program:

C program to list files of a directory


C program to list all files present in a directory/folder in which executable
file of this program is present. For example, if the executable file is present
in C:\\TC\\BIN then it will list all the files present in C:\\TC\\BIN.

C programming code (Turbo C compiler


only)
1. #include <stdio.h>
2. #include <conio.h>
3. #include <dir.h>
4.
5. int main()
6. {
7. int done;
8. struct ffblk a;
9.
10. printf("Press any key to view the files in the
current directory\n");
11.
12. getch();
13.
14. done = findfirst("*.*", &a, 0); // The first '*'
is for all file names and the second one is for all
file extensions
15.
16. while(!done)
17. {
18. printf("%s\n", a.ff_name);
19. done = findnext(&a);
20. }
21.
22. getch();
23. return 0;
24. }

Apparently, you will get a different output when you execute the program
on your computer.

C program to delete a file


C program to delete a file whose name a user will input, the file to be
deleted must 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
the error will be displayed by perror function.

C programming code
1. #include <stdio.h>
2.
3. int main()
4. {
5. int status;
6. char file_name[25];
7.
8. printf("Enter name of a file you wish to delete\n");
9. gets(file_name);
10.
11. status = remove(file_name);
12.
13. if (status == 0)
14. printf("%s file deleted
successfully.\n", file_name);
15. else
16. {
17. printf("Unable to delete the file\n");
18. perror("Following error occurred");
19. }
20.
21. return 0;
22. }

Download Delete file program executable.

Output of program:

The 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 specialized recovery
software, if they aren't overwritten on the storage medium.

C program to print date


C program to print current system date. To print date, we will use getdate
function.
C programming code (Works in Turbo C
only)
1. #include <stdio.h>
2. #include <conio.h>
3. #include <dos.h>
4.
5. int main()
6. {
7. struct date d;
8.
9. getdate(&d);
10.
11. printf("Current system date:
%d/%d/%d", d.da_day, d.da_mon, d.da_year);
12. getch();
13. return 0;
14. }

This code works in Turbo C only because it supports dos.h header file.

C program to get IP address


C program to print IP (Internet Protocol) address of your computer, system
function is used to execute the command "ipconfig" which prints IP
address, subnet mask, and default gateway. The code given below works for
Windows XP and Windows 7. If you are using Turbo C compiler then
execute this program from the folder, it may not work when you are
working in a compiler and trying to run it by Ctrl + F9.

C programming code
1. #include<stdlib.h>
2.
3. int main()
4. {
5. system("C:\\Windows\\System32\\ipconfig");
6.
7. return 0;
8. }
Download IP address program.

Output of program: (In Windows 7)

Only a part of the output is shown in the image.

C program to shut down or turn off computer


C program to shut down your computer: This program turns off, i.e., shut
down your computer system. System function of "stdlib.h" is used to run an
executable file shutdown.exe which is present in C:\WINDOWS\system32
folder in Windows 7 & XP. See Windows XP and Linux programs at the
bottom of this page.

C programming code for Windows 7


1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. system("C:\\WINDOWS\\System32\\shutdown /s");
7.
8. return 0;
9. }

You can use various options while executing shutdown.exe, for example,
you can use /t option to specify the number of seconds after which
shutdown occurs.
Syntax: "shutdown /s /t x"; where x is the number of seconds after which
shutdown will occur.

By default, shutdown occurs after 30 seconds. To shutdown immediately


you can write "shutdown /s /t 0". If you wish to restart your computer, then
you can use "shutdown /r."

C programming code for Windows XP


It will ask if you want to shutdown your computer, if you press 'y' then your
computer will shutdown in 30 seconds.

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. char ch;
7.
8. printf("Do you want to shutdown your computer now
(y/n)\n");
9. scanf("%c", &ch);
10.
11. if (ch == 'y' || ch == 'Y')
12. system("C:\\WINDOWS\\System32\\shutdown -s");
13.
14. return 0;
15. }

To shutdown immediately use "C:\\WINDOWS\\System32\\shutdown -s -


t 0". To restart use "-r" instead of "-s".

If you are using Turbo C Compiler then execute your program from
command prompt or by opening the executable file from the folder.
Press F9 to build your executable file from source program. When you run
program from within the compiler by pressing Ctrl+F9 it may not work.

C programming code for Ubuntu Linux


1. #include <stdio.h>
2.
3. int main() {
4. system("shutdown -P now");
5. return 0;
6. }

You need to be logged in as root user for this program to execute otherwise
you will get the message shutdown: Need to be root, now specifies that you
want to shut down immediately. '-P' option specifies you want to power off
your machine. You can specify minutes as:
shutdown -P "number of minutes."

For more options or help type "man shutdown" in terminal.

You might also like