C Practical For Computer Science
C Practical For Computer Science
" Program
In this example, you will learn to print "Hello, World!" on the screen in C
programming.
Output
Hello, World!
// displays output
printf("You entered: %d", number);
return 0;
}
Output
Enter an integer: 25
You entered: 25
int number;
Then, the user is asked to enter an integer number. This number is stored in
the number variable.
Finally, the value stored in number is displayed on the screen using printf() .
// calculating sum
sum = number1 + number2;
Output
In this program, the user is asked to enter two integers. These two integers
are stored in variables number1 and number2 respectively.
Then, these two numbers are added using the + operator, and the result is
stored in the sum variable.
// Calculating product
product = a * b;
return 0;
}
Output
In this program, the user is asked to enter two numbers which are stored in
variables a and b respectively.
Then, the product of a and b is evaluated and the result is stored in product .
product = a * b;
Notice that, the result is rounded off to the second decimal place
using %.2lf conversion character.
C Program to Find ASCII Value of a
Character
In this example, you will learn how to find the ASCII value of a character.
To understand this example, you should have the knowledge of the
following C programming topics:
• C Data Types
• C Variables, Constants and Literals
• C Input Output (I/O)
In C programming, a character variable holds ASCII value (an integer number
between 0 and 127) rather than that character itself. This integer value is the
ASCII code of the character.
For example, the ASCII value of 'A' is 65.
What this means is that, if you assign 'A' to a character variable, 65 is stored
in the variable rather than 'A' itself.
Now, let's see how we can print the ASCII value of characters in C
programming.
return 0;
}
Output
Enter a character: G
ASCII value of G = 71
In this program, the user is asked to enter a character. The character is stored
in variable c .
When %d format string is used, 71 (the ASCII value of G ) is displayed.
When %c format string is used, 'G' itself is displayed.
// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;
Output
Enter dividend: 25
Enter divisor: 4
Quotient = 6
Remainder = 1
In this program, the user is asked to enter two integers (dividend and divisor).
They are stored in variables dividend and divisor respectively.
Then the quotient is evaluated using / (the division operator), and stored
in quotient .
Similarly, the remainder is evaluated using % (the modulo operator) and stored
in remainder .
// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;
Enter dividend: 25
Enter divisor: 4
Quotient = 6
Remainder = 1
In this program, the user is asked to enter two integers (dividend and divisor).
They are stored in variables dividend and divisor respectively.
Then the quotient is evaluated using / (the division operator), and stored
in quotient .
Similarly, the remainder is evaluated using % (the modulo operator) and stored
in remainder .
return 0;
}
Output
return 0;
}
Output
In this program, the sizeof operator is used to find the size of int , long , long
Note: The long keyword cannot be used with float and char types.
Output
// swapping
// a = (initial_a - initial_b)
a = a - b;
return 0;
}
Output
Enter a: 10.25
Enter b: -12.5
After swapping, a = -12.50
After swapping, b = 10.25
return 0;
}
Output
Enter an integer: -7
-7 is odd.
In the program, the integer entered by the user is stored in the variable num .
Enter an integer: 33
33 is odd.
In the above program, we have used the ternary operator ?: instead of
the if...else statement.
Output
Enter an alphabet: G
G is a consonant.
Note: This program assumes that the user will enter an alphabet. If the user
enters a non-alphabetic character, it displays the character is a consonant.
To fix this, we can use the isalpha() function. The islapha() function checks
whether a character is an alphabet or not.
#include <ctype.h>
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
// evaluates to 1 if variable c is a lowercase vowel
lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
return 0;
}
Enter an alphabet: 3
Error! Non-alphabetic character.
int main() {
return 0;
}
int main() {
return 0;
}
int main() {
// outer if statement
if (n1 >= n2) {
// inner if...else
if (n1 >= n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
// inner if...else
if (n2 >= n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.", n3);
}
return 0;
}
In this program, we have used nested if...else statements to find the largest
number. Let's see how they work in greater detail.
1. Outer if Statement
First, notice the outer if statement and the inner if...else statement inside it:
// outer if statement
if (n1 >= n2) {
// inner if...else
if (n1 >= n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
The inner if...else of this part of the program uses the same logic as the one
before. The only difference here is that we're checking if n2 is greater than n3 .
The output of all these programs above will be the same.
ax2 + bx + c = 0, where
a, b and c are real numbers and
a != 0
The term b2; - 4ac is known as the discriminant of a quadratic equation. It tells
the nature of the roots.
• If the discriminant is greater than 0 , the roots are real and different.
• If the discriminant is equal to 0 , the roots are real and equal.
• If the discriminant is less than 0 , the roots are complex and different.
Figure: Roots of a Quadratic Equation
discriminant = b * b - 4 * a * c;
return 0;
}
Output
In this program, the sqrt() library function is used to find the square root of a
number. To learn more, visit: sqrt() function.
For example,
return 0;
}
Output 1
Output 2
int main() {
double num;
printf("Enter a number: ");
scanf("%lf", &num);
if (num <= 0.0) {
if (num == 0.0)
printf("You entered 0.");
else
printf("You entered a negative number.");
}
else
printf("You entered a positive number.");
return 0;
}
You can also solve this problem using nested if...else statement.
int main() {
double num;
printf("Enter a number: ");
scanf("%lf", &num);
return 0;
}
Output 1
Output 2
Enter a number: 0
You entered 0.
C Program to Check Whether a
Character is an Alphabet or not
In this example, you will learn to check whether a character entered by the
user is an alphabet or not.
The ASCII value of the lowercase alphabet is from 97 to 122. And, the ASCII
value of the uppercase alphabet is from 65 to 90.
If the ASCII value of the character entered by the user lies in the range of 97
to 122 or from 65 to 90, that number is an alphabet.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);
return 0;
}
Output
Enter a character: *
* is not an alphabet
In the program, 'a' is used instead of 97 and 'z' is used instead of 122 .
if (isalpha(c))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);
sum = 1 + 2 + 3 + ... + 10
Sum of Natural Numbers Using for Loop
#include <stdio.h>
int main() {
int n, i, sum = 0;
The above program takes input from the user and stores it in the variable n .
Then, for loop is used to calculate the sum up to n .
while (i <= n) {
sum += i;
++i;
}
Output
do {
printf("Enter a positive integer: ");
scanf("%d", &n);
} while (n <= 0);
Visit this page to learn how to find the sum of natural numbers using
recursion.
C Program to Find Factorial of a
Number
In this example, you will learn to calculate the factorial of a number entered by
the user.
Factorial of a Number
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
return 0;
}
Output
Enter an integer: 10
Factorial of 10 = 3628800
This program takes a positive integer from the user and computes the factorial
using for loop.
Since the factorial of a number may be very large, the type of factorial variable
is declared as unsigned long long .
If the user enters a negative number, the program displays a custom error
message.
C Program to Generate
Multiplication Table
In this example, you will learn to generate the multiplication table of a number
entered by the user.
The program below takes an integer input from the user and generates the
multiplication tables up to 10.
Multiplication Table Up to 10
#include <stdio.h>
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
Output
Enter an integer: 9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
Here, the user input is stored in the int variable n . Then, we use a for loop to
print the multiplication table up to 10.
int n, i, range;
printf("Enter an integer: ");
scanf("%d", &n);
return 0;
}
Output
Enter an integer: 12
Enter the range (positive integer): -8
Enter the range (positive integer): 8
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
Here, we have used a do...while loop to prompt the user for a positive range.
If the value of range is negative, the loop iterates again to ask the user to enter
a positive number. Once a positive range has been entered, we print the
multiplication table.
int i, n;
return 0;
}
Output
Let us suppose n = 10 . First, we have printed the first two terms of the
Fibonacci sequence before using a for loop to print the next n terms.
Let us see how the for loop works:
i t1 t2 nextTerm
3 0 1 1
4 1 1 2
5 1 2 3
6 2 3 5
7 3 5 8
8 5 8 13
9 8 13 21
10 13 21 34
return 0;
}
Output
In this program, we have used a while loop to print all the Fibonacci numbers
up to n .
If n is not part of the Fibonacci sequence, we print the sequence up to the
number that is closest to (and lesser than) n .
Suppose n = 100 . First, we print the first two terms t1 = 0 and t2 = 1 .
Then the while loop prints the rest of the sequence using the nextTerm variable:
int main() {
while (1) {
if ((max % n1 == 0) && (max % n2 == 0)) {
printf("The LCM of %d and %d is %d.", n1, n2, max);
break;
}
++max;
}
return 0;
}
Output
If this test condition is not true, max is incremented by 1 and the iteration
continues until the test expression of the if statement is true.
We can also find the LCM of two numbers num1 and num2 using their GCD:
Learn how to find the GCD of two numbers in C programming before finding
the LCM with this method.
#include <stdio.h>
int main() {
Output
Output
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In this program, the for loop is used to display the English alphabet in
uppercase.
Here's a little modification of the above program. The program displays the
English alphabet in either uppercase or lowercase depending upon the input
given by the user.
Print Lowercase/Uppercase alphabets
#include <stdio.h>
int main() {
char c;
printf("Enter u to display uppercase alphabets.\n");
printf("Enter l to display lowercase alphabets. \n");
scanf("%c", &c);
if (c == 'U' || c == 'u') {
for (c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
} else if (c == 'L' || c == 'l') {
for (c = 'a'; c <= 'z'; ++c)
printf("%c ", c);
} else {
printf("Error! You entered an invalid character.");
}
return 0;
}
Output
Output
Note: We have used a do...while loop to ensure that we get the correct digit
count when the user enters 0.
C Program to Reverse a Number
In this example, you will learn to reverse the number entered by the user.
int main() {
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}
return 0;
}
Output
This program takes integer input from the user. Then the while loop is used
until n != 0 is false (0).
In each iteration of the loop, the remainder when n is divided by 10 is
calculated and the value of n is reduced by 10 times.
Inside the loop, the reversed number is computed using:
n n != 0 remainder reverse
2345 true 5 0 * 10 + 5 = 5
234 true 4 5 * 10 + 4 = 54
23 true 3 54 * 10 + 3 = 543
Finally, the reverse variable (which contains the reversed number) is printed on
the screen.
• 3 is the exponent
while (exp != 0) {
result *= base;
--exp;
}
printf("Answer = %.0Lf", result);
return 0;
}
Output
We can also use the pow() function to calculate the power of a number.
Power Using pow() Function
#include <math.h>
#include <stdio.h>
int main() {
double base, exp, result;
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent: ");
scanf("%lf", &exp);
Output
The programs above can only calculate the power of the base number if the
exponent is positive. For negative exponents, use the following mathematical
logic:
base(-exponent) = 1 / (baseexponent)
For example,
2-3 = 1 / (23)
C Program to Check Whether a
Number is Palindrome or Not
In this example, you will learn to check whether the number entered by the
user is a palindrome or not.
Output
Here, the user is asked to enter an integer. The number is stored in variable n .
We then assigned this number to another variable orignal . Then, the reverse
of n is found and stored in reversed .
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
return 0;
}
Output
if (n % i == 0) {
flag = 1;
break;
}
int main() {
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Prime numbers between %d and %d are: ", low, high);
if (low % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", low);
return 0;
}
Output
Visit this page to learn more about how to check whether a number is prime or
not.
If the user enters the larger number first, the above program doesn't work as
intended. You can solve this issue by swapping the numbers.
Display Prime Numbers when Larger Number is Entered first
#include <stdio.h>
int main() {
int low, high, i, flag, temp;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
return 0;
}
Visit this page to learn how you can display all the prime numbers between
the two intervals by creating a user-defined function
abcd... = an + bn + cn + dn +
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit
is equal to the number itself. For example, 153 is an Armstrong number
because
153 = 1*1*1 + 5*5*5 + 3*3*3
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
Output
int main() {
int num, originalNum, remainder, n = 0;
float result = 0.0;
originalNum = num;
Output
In this program, the number of digits of an integer is calculated first and stored
in n . And, the pow() function is used to compute the power of individual digits in
each iteration of the second for loop.
C Program to Display Armstrong
Number Between Two Intervals
In this example, you will learn to find all Armstrong numbers between two
integers entered by the user.
abcd... = an + bn + cn + dn +
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit
is equal to the number itself. For example, 153 is an Armstrong number
because
In this program, we will print all the Armstrong numbers between two integers.
This means that the two integers will not be part of the range, but only those
integers that are between them.
For example, suppose we want to print all Armstrong numbers
between 153 and 371. Both of these numbers are also Armstrong numbers.
Then, this program prints all Armstrong numbers that are greater
than 153 and less than 371 i.e. 153 and 371 won't be printed even though
they are Armstrong numbers.
Tip: Before trying this program, learn how to check whether an integer is an
Armstrong number or not.
originalNumber = number;
return 0;
}
Run Code
Output
In the program, the outer loop is iterated from (low+ 1) to (high - 1). In each
iteration, it's checked whether number is an Armstrong number or not.
Inside the outer loop, the number of digits of an integer is calculated first and
stored in count . And, the sum of the power of individual digits is stored in
the result variable.
If number is equal to result , the number is an Armstrong number.
Notes:
• You need to swap low and high if the user input for high is less than that
of low . To learn more, check our example on swapping two numbers.
• You need to reset count and result to 0 in each iteration of the outer loop.
C Program to Display Factors of a
Number
In this example, you will learn to find all the factors of an integer entered by
the user.
Output
if (num % i == 0) {
printf("%d ", i);
}
int main() {
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
To make our output look cleaner, we have simply limited the output to one
decimal place using the code %.1lf .
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
Output
Explanation
int checkPrimeNumber(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
Output
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);
return 0;
}
return isPrime;
}
Output
So, we print the result on the screen and change the value of flag to 1 .
Otherwise, flag remains 0 .
This process continues until the loop ends.
If flag is still 0 , then we know that n can't be expressed as the sum of two
primes, and we print that message on the screen.
C Program to Find the Sum of
Natural Numbers using Recursion
In this example, you will learn to find the sum of natural numbers using a
recursive function.
Visit this page to find the sum of natural numbers using a loop.
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d", addNumbers(num));
return 0;
}
int addNumbers(int n) {
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
}
Output
Output
Visit this page to learn how you can calculate the GCD using loops.
In this program, recursive calls are made until the value of n2 is equal to 0.
#include <stdio.h>
#include <math.h>
// function prototype
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
// function definition
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Output
5 + 1 * pow (2, 3) =
1 != 0 1 % 10 = 1 1 / 10 = 0 3
13
So, 1101 in binary is 13 in decimal.
Now, let's see how we can change the decimal number into a binary number.
#include <stdio.h>
#include <math.h>
int main() {
int n, bin;
printf("Enter a decimal number: ");
scanf("%d", &n);
bin = convert(n);
printf("%d in decimal = %lld in binary", n, bin);
return 0;
}
while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
Output
Suppose n = 13 . Let's see how the while loop in the convert() function works.
rem =
n != 0 n /= 2 i bin += rem * i i * = 10
n%2
13 % 13 / 2
13 != 0 1 0+1*1=1 1 * 10 = 10
2=1 =6
6%2 6/2=
6 != 0 10 1 + 0 * 10 = 1 10 * 10 = 100
=0 3
Loop
0 != 0 - - -
terminates
// function prototype
int convertDecimalToOctal(int decimalNumber);
int main() {
int decimalNumber;
return 0;
}
while (decimalNumber != 0) {
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
Output
// function prototype
long long convertOctalToDecimal(int octalNumber);
int main() {
int octalNumber;
return 0;
}
while(octalNumber != 0) {
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
return decimalNumber;
}
Output
// function prototypes
int checkOctal(int);
long long convertOctalToDecimal(int);
int main() {
int octalNumber;
int condition;
if (!condition) {
printf("%d is not an octal number!\n", octalNumber);
}
} while (condition == 0);
return 0;
}
// return 0 if a digit is 8 or 9
if (remainder >= 8) {
return 0;
}
octalNumber/= 10;
}
while(octalNumber != 0) {
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
return decimalNumber;
}
In this program, we will first convert a binary number to decimal. Then, the
decimal number is converted to octal.
#include <math.h>
#include <stdio.h>
int convert(long long bin);
int main() {
long long bin;
printf("Enter a binary number: ");
scanf("%lld", &bin);
printf("%lld in binary = %d in octal", bin, convert(bin));
return 0;
}
Output
#include <math.h>
#include <stdio.h>
long long convert(int oct);
int main() {
int oct;
printf("Enter an octal number: ");
scanf("%d", &oct);
printf("%d in octal = %lld in binary", oct, convert(oct));
return 0;
}
Output
Output
This program first prints Enter a sentence: . Then, the reverseSentence() function is
called.
This function stores the first letter entered by the user in c . If the variable is
any character other than \n (newline), reverseSentence() is called again.
This process goes on until the user hits enter.
When the user hits enter, the reverseSentence() function starts printing
characters from last.
Output
Here, the user is first asked to enter the number of elements. This number is
assigned to n .
If the user entered integer is greater less than 1 or greater than 100, the user
is asked to enter the number again. This is done using a while loop.
Then, we have iterated a for loop from i = 0 to i . In each iteration of the loop,
the user is asked to enter numbers to calculate the average. These numbers are stored in
scanf("%f", &num[i]);
sum += num[i];
Once the for loop is completed, the average is calculated and printed on the
screen.
C Program to Find Largest Element
in an Array
In this example, you will learn to display the largest element entered by the
user in an array.
return 0;
}
Output
This program takes n number of elements from the user and stores it in
the arr array.
To find the largest element,
• the first two elements of array are checked and the largest of these two
elements are placed in arr[0]
• the first and third elements are checked and largest of these two
elements is placed in arr[0] .
• this process continues until the first and last elements are checked
Output
Enter 10 elements: 1
2
3
4
5
6
7
8
9
10
return 0;
}
Output
10 8 6
In this program, the user is asked to enter the number of rows r and
columns c . Then, the user is asked to enter the elements of the two matrices
(of order rxc ).
To multiply two matrices, the number of columns of the first matrix should
be equal to the number of rows of the second matrix.
The program below asks for the number of rows and columns of two matrices
until the above condition is satisfied.
printf("\nOutput Matrix:\n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("%d ", result[i][j]);
if (j == column - 1)
printf("\n");
}
}
}
int main() {
int first[10][10], second[10][10], result[10][10], r1, c1, r2, c2;
printf("Enter rows and column for the first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for the second matrix: ");
scanf("%d %d", &r2, &c2);
Output
Enter elements:
Enter a11: 2
Enter a12: -3
Enter a13: 4
Enter a21: 53
Enter a22: 3
Enter a23: 5
Enter elements:
Enter a11: 3
Enter a12: 3
Enter a21: 5
Enter a22: 0
Enter a31: -3
Enter a32: 4
Output Matrix:
-21 22
159 179
C Program to Find Transpose of a
Matrix
In this example, you will learn to find the transpose of a matrix in C
programming.
In this program, the user is asked to enter the number of rows r and
columns c . Their values should be less than 10 in this program.
Then, the user is asked to enter the elements of the matrix (of order r*c ).
The program below then computes the transpose of the matrix and prints it on
the screen.
Output
Entered matrix:
1 4 0
-5 2 7
Transpose of the matrix:
1 -5
4 2
0 7
Then, it asks the user to enter the elements of those matrices and finally adds
and displays the result.
#include <stdio.h>
int main()
{
int firstMatrix[10][10], secondMatrix[10][10], mult[10][10], rowFirst,
columnFirst, rowSecond, columnSecond, i, j, k;
// If colum of first matrix in not equal to row of second matrix, asking user to
enter the size of matrix again.
while (columnFirst != rowSecond)
{
printf("Error! column of first matrix not equal to row of second.\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &rowFirst, &columnFirst);
printf("Enter rows and column for second matrix: ");
scanf("%d%d", &rowSecond, &columnSecond);
}
Output
Output Matrix:
24 29
6 25
Output
Enter elements: 1
2
3
5
4
You entered:
1
2
3
5
4
In this program, the elements are stored in the integer array data[] .
Then, the elements of the array are accessed using the pointer notation. By
the way,
• ...
return 0;
}
Output
int main() {
int n;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
free(data);
return 0;
}
Output
Explanation
In the program, we have asked the user to enter the total number of elements
which is stored in the variable n . Then, we have allocated memory
for n number of double values.
Then, we used a for loop to take n number of data from the user.
// Storing elements
for (int i = 0; i < n; ++i) {
printf("Enter Number%d: ", i + 1);
scanf("%lf", data + i);
}
Note: Instead of calloc() , it's also possible to solve this problem using
the malloc() function.
Output
Then, the user is asked to enter the character whose frequency is to be found.
This is stored in variable ch .
Then, a for loop is used to iterate over characters of the string. In each
iteration, if the character in the string is equal to the ch , count is increased by 1.
Finally, the frequency stored in the count variable is printed.
char line[150];
int vowels, consonant, digit, space;
return 0;
}
Output
Here, the string entered by the user is stored in the line variable.
Initially, the variables vowel , consonant , digit, and space are initialized to 0.
Then, a for loop is used to iterate over the characters of the string. In each
iteration, we:
• convert the character to lowercase using the tolower() function
• check whether the character is a vowel, a consonant, a digit, or an
empty space. Suppose the character is a consonant. Then,
the consonant variable is increased by 1.
When the loop ends, the number of vowels, consonants, digits, and white
spaces are stored in variables vowel , consonant , digit, and space respectively.
Note: We have used the tolower() function to simplify our program. To use
this function, we need to import the ctype.h header file.
C Program to Remove all
Characters in a String Except
Alphabets
In this example, you will learn to remove all the characters from a string
entered by the user except the alphabets.
Output
This program takes a string input from the user and stores in the line variable.
Then, a for loop is used to iterate over characters of the string.
If the character in a string is not an alphabet, it is removed from the string and
the position of the remaining characters are shifted to the left by 1 position.
Output
Here, using a for loop, we have iterated over characters of the string from i =
Note: Here, the array s[] has 19 elements. The last element s[18] is the null
character '\0' . But our loop does not count this character as it terminates
upon encountering it.
C Program to Concatenate Two
Strings
In this example, you will learn to concatenate two strings manually without
using the strcat() function.
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}
return 0;
}
Output
Here, two strings s1 and s2 and concatenated and the result is stored in s1 .
It's important to note that the length of s1 should be sufficient to hold the string
after concatenation. If not, you may get unexpected output.
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output
int main() {
char str[5][50], temp[50];
printf("Enter 5 words: ");
int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}
Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
struct Distance {
int feet;
float inch;
} d1, d2, result;
int main() {
// take first distance input
printf("Enter 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);
// adding distances
result.feet = d1.feet + d2.feet;
result.inch = d1.inch + d2.inch;
Output
int main() {
complex n1, n2, result;
Output
int main() {
struct TIME startTime, stopTime, diff;
Output
In this program, the user is asked to enter two time periods and these two
periods are stored in structure variables startTime and stopTime respectively.
Then, the function differenceBetweenTimePeriod() calculates the difference
between the time periods. The result is displayed from the main() function
without returning it (using call by reference technique).
C Program to Store Information of
Students Using Structure
In this example, you will learn to store the information of 5 students by using
an array of structures.
int main() {
int i;
printf("Enter information of students:\n");
// storing information
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");
// displaying information
for (i = 0; i < 5; ++i) {
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
return 0;
}
Output
Roll number: 1
Name: Tom
Marks: 98
.
.
.
int main() {
struct course *ptr;
int noOfRecords;
printf("Enter the number of records: ");
scanf("%d", &noOfRecords);
printf("Displaying Information:\n");
for (int i = 0; i < noOfRecords; ++i) {
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
}
free(ptr);
return 0;
}
Output
Displaying Information:
Science 82
DSA 73
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
Output
Here, a file named program.txt is created. The file will contain C programming is fun
text.
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! File cannot be opened.");
// Program exits if the file pointer returns NULL.
exit(1);
}
return 0;
}
If the file is found, the program saves the content of the file to a
string c until '\n' newline is encountered.
Suppose the program.txt file contains the following text in the current directory.
C programming is awesome.
I love C programming.
How are you doing?
If the file program.txt is not found, the program prints the error message.
#include <stdio.h>
int main() {
printf("%s",__FILE__);
#include <stdio.h>
int main() {
FILE *fp;
int c;
do {
c = getc(fp); // read character
putchar(c); // display character
}
while(c != EOF); // loop until the end of file is reached
fclose(fp);
return 0;
}
C Program to Print Pyramids and
Patterns
In this example, you will learn to print half pyramids, inverted pyramids, full
pyramids, inverted full pyramids, Pascal's triangle, and Floyd's triangle in C
Programming.
To understand this example, you should have the knowledge of the following C
programming topics:
• C if...else Statement
• C for Loop
• C while and do...while Loop
• C break and continue
Here is a list of programs you will find in this page.
C Examples
Half pyramid of *
Full pyramid of *
C Examples
Pascal's triangle
Floyd's triangle
*
* *
* * *
* * * *
* * * * *
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
Example 2: Half Pyramid of Numbers
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
A
B B
C C C
D D D D
E E E E E
C Program
#include <stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {
printf("%c ", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}
* * * * *
* * * *
* * *
* *
*
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
C Program
#include <stdio.h>
int main() {
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
Example 7: Full Pyramid of Numbers
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
C Program
#include <stdio.h>
int main() {
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
printf("%d ", i + k);
++count;
} else {
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
Example 8: Inverted full pyramid of *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
C Program
#include <stdio.h>
int main() {
int rows, i, j, space;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (space = 0; space < rows - i; ++space)
printf(" ");
for (j = i; j <= 2 * i - 1; ++j)
printf("* ");
for (j = 0; j < i - 1; ++j)
printf("* ");
printf("\n");
}
return 0;
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
C Program
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
Example 10: Floyd's Triangle.
1
2 3
4 5 6
7 8 9 10
C Program
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}