1
Hello World
#include
int main()
{
printf("Hello World");
return 0;
}
2
Print an Integer
#include
int main() {
int number;
printf("Enter an integer: ");
// reads and stores input
scanf("%d", &number);
// displays output
printf("You entered: %d", number);
return 0;
}
3
Add Two Integers
#include
int main() {
int number1, number2, sum;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
// calculate the sum
sum = number1 + number2;
printf("%d + %d = %d", number1, number2, sum);
return 0;
}
4
Multiply Two Numbers
#include
int main() {
double a, b, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
// Calculating product
product = a * b;
// %.2lf displays number up to 2 decimal point
printf("Product = %.2lf", product);
return 0;
}
5
ASCII value
#include
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
6
Compute Quotient and Remainder
#include
int main() {
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d", ÷nd);
printf("Enter divisor: ");
scanf("%d", &divisor);
// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;
printf("Quotient = %d\n", quotient);
printf("Remainder = %d", remainder);
return 0;
}
7
Find the Size of Variables
#include
int main() {
int intType;
float floatType;
double doubleType;
char charType;
// sizeof evaluates the size of a variable
printf("Size of int: %zu bytes\n", sizeof(intType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));
return 0;
}
8
Using the long keyword
Using the long keyword
#include
int main() {
int a;
long b; // equivalent to long int b;
long long c; // equivalent to long long int c;
double e;
long double f;
printf("Size of int = %zu bytes \n", sizeof(a));
printf("Size of long int = %zu bytes\n", sizeof(b));
printf("Size of long long int = %zu bytes\n", sizeof(c));
printf("Size of double = %zu bytes\n", sizeof(e));
printf("Size of long double = %zu bytes\n", sizeof(f));
return 0;
}
9
Swap Numbers
Swap Numbers Using Temporary Variable
#include
int main() {
double first, second, temp;
printf("Enter first number: ");
scanf("%lf", &first);
printf("Enter second number: ");
scanf("%lf", &second);
// value of first is assigned to temp
temp = first;
// value of second is assigned to first
first = second;
// value of temp (initial value of first) is assigned to second
second = temp;
// %.2lf displays number up to 2 decimal points
printf("\nAfter swapping, first number = %.2lf\n", first);
printf("After swapping, second number = %.2lf", second);
return 0;
}
`10
Check Even or Odd
Check Even or Odd
#include
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
// true if num is perfectly divisible by 2
if(num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);
return 0;
}
11
Check Vowel or consonant
Check Vowel or consonant
#include
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');
// evaluates to 1 if variable c is a uppercase vowel
uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// evaluates to 1 (true) if c is a vowel
if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
12
Using if Statement
Using if Statement
#include
int main() {
double n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
// if n1 is greater than both n2 and n3, n1 is the largest
if (n1 >= n2 && n1 >= n3)
printf("%.2f is the largest number.", n1);
// if n2 is greater than both n1 and n3, n2 is the largest
if (n2 >= n1 && n2 >= n3)
printf("%.2f is the largest number.", n2);
// if n3 is greater than both n1 and n2, n3 is the largest
if (n3 >= n1 && n3 >= n2)
printf("%.2f is the largest number.", n3);
return 0;
}
13
Roots of a Quadratic Equatio
#include
#include
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
14
leap year
#include
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
// leap year if perfectly divisible by 400
if (year % 400 == 0) {
printf("%d is a leap year.", year);
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", year);
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0) {
printf("%d is a leap year.", year);
}
// all other years are not leap years
else {
printf("%d is not a leap year.", year);
}
return 0;
}
15
Positive or Negative
Positive or Negative Using Nested if...else
#include
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;
}
16
Check Alphabet
Check Alphabet
#include
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);
return 0;
}
17
Natural Numbers
Natural Numbers Using for Loop
#include
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum = %d", sum);
return 0;
}
18
Factorial of a Number
Factorial of a Number
#include
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
19
Multiplication Table
Multiplication Table Up to 10
#include
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
for (int i = 1; i <= 10; ++i) {
printf("%d * %d = %d \n", n, i, n * i);
}
return 0;
}
20
Fibonacci Series up to n terms
Fibonacci Series up to n terms
#include
int main() {
int i, n;
// initialize first and second terms
int t1 = 0, t2 = 1;
// initialize the next term (3rd term)
int nextTerm = t1 + t2;
// get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n);
// print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2);
// print 3rd to nth terms
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
21
GCD
GCD Using for loop and if Statement
#include
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}
22
LCM
LCM using while and if
#include
int main() {
int n1, n2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// maximum number between n1 and n2 is stored in max
max = (n1 > n2) ? n1 : n2;
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;
}
23
Print English Alphabets
Print English Alphabets
#include
int main() {
char c;
for (c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
return 0;
}
24
Count the Number of Digits
Count the Number of Digits
#include
int main() {
long long n;
int count = 0;
printf("Enter an integer: ");
scanf("%lld", &n);
// iterate at least once, then until n becomes 0
// remove last digit from n in each iteration
// increase count by 1 in each iteration
do {
n /= 10;
++count;
} while (n != 0);
printf("Number of digits: %d", count);
}
25
Reverse an Integer
Reverse an Integer
#include
int main() {
int n, reverse = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}
printf("Reversed number = %d", reverse);
return 0;
}
26
Power of a Number
Power of a Number Using the while Loop
#include
int main() {
int base, exp;
long double result = 1.0;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exp);
while (exp != 0) {
result *= base;
--exp;
}
printf("Answer = %.0Lf", result);
return 0;
}
27
Check Palindrome
Check Palindrome
#include
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
// reversed integer is stored in reversed variable
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
// palindrome if orignal and reversed are equal
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
28
prime number
#include
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
29
Display Prime Numbers Between Two Intervals
#include
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);
// iteration until low is not equal to high
while (low < high) {
flag = 0;
// ignore numbers less than 2
if (low <= 1) {
++low;
continue;
}
// if low is a non-prime number, flag will be 1
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", low);
// to check prime for the next number
// increase low by 1
++low;
}
return 0;
}
30
Armstrong number
#include
int main() {
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the orignal number
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
31
Armstrong Numbers Between Two Integers
#include
#include
int main() {
int low, high, number, originalNumber, rem, count = 0;
double result = 0.0;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d and %d are: ", low, high);
// swap numbers if high < low
if (high < low) {
high += low;
low = high - low;
high -= low;
}
// iterate number from (low + 1) to (high - 1)
// In each iteration, check if number is Armstrong
for (number = low + 1; number < high; ++number) {
originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++count;
}
originalNumber = number;
// result contains sum of nth power of individual digits
while (originalNumber != 0) {
rem = originalNumber % 10;
result += pow(rem, count);
originalNumber /= 10;
}
// check if number is equal to the sum of nth power of individual digits
if ((int)result == number) {
printf("%d ", number);
}
// resetting the values
count = 0;
result = 0;
}
return 0;
}
32
Factors of a Positive Integer
Factors of a Positive Integer
#include
int main() {
int num, i;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Factors of %d are: ", num);
for (i = 1; i <= num; ++i) {
if (num % i == 0) {
printf("%d ", i);
}
}
return 0;
}
33
Simple Calculator
Simple Calculator using switch Statement
#include
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;
}
34
Prime Numbers Between Two Integers
Prime Numbers Between Two Integers
#include
int checkPrimeNumber(int n);
int main() {
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// swap n1 and n2 if n1 > n2
if (n1 > n2) {
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
}
printf("Prime numbers between %d and %d are: ", n1, n2);
for (i = n1 + 1; i < n2; ++i) {
// flag will be equal to 1 if i is prime
flag = checkPrimeNumber(i);
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
35
Prime and Armstrong
Check Prime and Armstrong
#include
#include
int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
// check prime number
flag = checkPrimeNumber(n);
if (flag == 1)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
// check Armstrong number
flag = checkArmstrongNumber(n);
if (flag == 1)
printf("%d is an Armstrong number.", n);
else
printf("%d is not an Armstrong number.", n);
return 0;
}
// function to check prime number
int checkPrimeNumber(int n) {
int i, flag = 1, squareRoot;
// computing the square root
squareRoot = sqrt(n);
for (i = 2; i <= squareRoot; ++i) {
// condition for non-prime number
if (n % i == 0) {
flag = 0;
break;
}
}
return flag;
}
// function to check Armstrong number
int checkArmstrongNumber(int num) {
int originalNum, remainder, n = 0, flag;
double result = 0.0;
// store the number of digits of num in n
for (originalNum = num; originalNum != 0; ++n) {
originalNum /= 10;
}
for (originalNum = num; originalNum != 0; originalNum /= 10) {
remainder = originalNum % 10;
// store the sum of the power of individual digits in result
result += pow(remainder, n);
}
// condition for Armstrong number
if (round(result) == num)
flag = 1;
else
flag = 0;
return flag;
}
36
integer as a Sum of Two Prime Numbers
#include
int checkPrime(int n);
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
// condition for i to be a prime number
if (checkPrime(i) == 1) {
// condition for n-i to be a prime number
if (checkPrime(n - i) == 1) {
printf("%d = %d + %d\n", n, i, n - i);
flag = 1;
}
}
}
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);
return 0;
}
// function to check prime number
int checkPrime(int n) {
int i, isPrime = 1;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}
37
Sum of Natural Numbers
Sum of Natural Numbers Using Recursion
#include
int addNumbers(int n);
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;
}
38
Factorial of a Number Using Recursion
Factorial of a Number Using Recursion
#include
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
39
GCD of Two Numbers
GCD of Two Numbers using Recursion
#include
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
40
Convert Binary Number to Decimal
C Program to Convert Binary Number to Decimal
// convert binary to decimal
#include
#include
// 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) {
// get remainder of n divided by 10
rem = n % 10;
// divide n by 10
n /= 10;
// multiply rem by (2 ^ i)
// add the product to dec
dec += rem * pow(2, i);
// increment i
++i;
}
return dec;
}
41
Convert Decimal to Octal
Convert Decimal to Octal
#include
#include
// function prototype
int convertDecimalToOctal(int decimalNumber);
int main() {
int decimalNumber;
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
printf("%d in decimal = %d in octal", decimalNumber, convertDecimalToOctal(decimalNumber));
return 0;
}
// function to convert decimalNumber to octal
int convertDecimalToOctal(int decimalNumber) {
int octalNumber = 0, i = 1;
while (decimalNumber != 0) {
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
42
decimal number is converted to octal.
the decimal number is converted to octal.
#include
#include
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;
}
int convert(long long bin) {
int oct = 0, dec = 0, i = 0;
// converting binary to decimal
while (bin != 0) {
dec += (bin % 10) * pow(2, i);
++i;
bin /= 10;
}
i = 1;
// converting to decimal to octal
while (dec != 0) {
oct += (dec % 8) * i;
dec /= 8;
i *= 10;
}
return oct;
}
43
Reverse a sentence
Reverse a sentence using recursion
#include
void reverseSentence();
int main() {
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
void reverseSentence() {
char c;
scanf("%c", &c);
if (c != '\n') {
reverseSentence();
printf("%c", c);
}
}
44
calculate power
Program to calculate power using recursion
#include
int power(int n1, int n2);
int main() {
int base, a, result;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}
int power(int base, int a) {
if (a != 0)
return (base * power(base, a - 1));
else
return 1;
}
45
Store Numbers and Calculate Average
Store Numbers and Calculate Average Using Arrays
#include
int main() {
int n, i;
float num[100], sum = 0.0, avg;
printf("Enter the numbers of elements: ");
scanf("%d", &n);
while (n > 100 || n < 1) {
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Enter number: ", i + 1);
scanf("%f", &num[i]);
sum += num[i];
}
avg = sum / n;
printf("Average = %.2f", avg);
return 0;
}
46
Largest Element in an array
Largest Element in an array
#include
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);
}
// storing the largest number to arr[0]
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
printf("Largest element = %.2lf", arr[0]);
return 0;
}
47
Population Standard Deviation
Example: Population Standard Deviation
// SD of a population
#include
#include
float calculateSD(float data[]);
int main() {
int i;
float data[10];
printf("Enter 10 elements: ");
for (i = 0; i < 10; ++i)
scanf("%f", &data[i]);
printf("\nStandard Deviation = %.6f", calculateSD(data));
return 0;
}
float calculateSD(float data[]) {
float sum = 0.0, mean, SD = 0.0;
int i;
for (i = 0; i < 10; ++i) {
sum += data[i];
}
mean = sum / 10;
for (i = 0; i < 10; ++i) {
SD += pow(data[i] - mean, 2);
}
return sqrt(SD / 10);
}
48
Add Two Matrices
Program to Add Two Matrices
#include
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
49
Multiply Matrices
Multiply Matrices by Passing it to a Function
#include
// function to get matrix elements entered by the user
void getMatrixElements(int matrix[][10], int row, int column) {
printf("\nEnter elements: \n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}
// function to multiply two matrices
void multiplyMatrices(int first[][10],
int second[][10],
int result[][10],
int r1, int c1, int r2, int c2) {
// Initializing elements of matrix mult to 0.
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
result[i][j] = 0;
}
}
// Multiplying first and second matrices and storing it in result
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
}
// function to display the matrix
void display(int result[][10], int row, int column) {
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);
// Taking input until
// 1st matrix columns is not equal to 2nd matrix row
while (c1 != r2) {
printf("Error! Enter rows and columns again.\n");
printf("Enter rows and columns for the first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns for the second matrix: ");
scanf("%d%d", &r2, &c2);
}
// get elements of the first matrix
getMatrixElements(first, r1, c1);
// get elements of the second matrix
getMatrixElements(second, r2, c2);
// multiply two matrices.
multiplyMatrices(first, second, result, r1, c1, r2, c2);
// display the result
display(result, r1, c2);
return 0;
}
50
Find the Transpose of a Matrix
Program to Find the Transpose of a Matrix
#include
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// printing the matrix a[][]
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
// computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
51
Multiply Matrices by Passing it to a Function
Multiply Matrices by Passing it to a Function
#include
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond);
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int multResult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond);
void display(int mult[][10], int rowFirst, int columnSecond);
int main()
{
int firstMatrix[10][10], secondMatrix[10][10], mult[10][10], rowFirst, columnFirst, rowSecond, columnSecond, i, j, k;
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);
// 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);
}
// Function to take matrices data
enterData(firstMatrix, secondMatrix, rowFirst, columnFirst, rowSecond, columnSecond);
// Function to multiply two matrices.
multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond);
// Function to display resultant matrix after multiplication.
display(mult, rowFirst, columnSecond);
return 0;
}
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond)
{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnFirst; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &firstMatrix[i][j]);
}
}
printf("\nEnter elements of matrix 2:\n");
for(i = 0; i < rowSecond; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
printf("Enter elements b%d%d: ", i + 1, j + 1);
scanf("%d", &secondMatrix[i][j]);
}
}
}
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int mult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond)
{
int i, j, k;
// Initializing elements of matrix mult to 0.
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
mult[i][j] = 0;
}
}
// Multiplying matrix firstMatrix and secondMatrix and storing in array mult.
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
52
Access Array Elements
Access Array Elements Using Pointers
#include
int main() {
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
53
Swap Elements Using Call by Reference
Program to Swap Elements Using Call by Reference
#include
void cyclicSwap(int *a, int *b, int *c);
int main() {
int a, b, c;
printf("Enter a, b and c respectively: ");
scanf("%d %d %d", &a, &b, &c);
printf("Value before swapping:\n");
printf("a = %d \nb = %d \nc = %d\n", a, b, c);
cyclicSwap(&a, &b, &c);
printf("Value after swapping:\n");
printf("a = %d \nb = %d \nc = %d", a, b, c);
return 0;
}
void cyclicSwap(int *n1, int *n2, int *n3) {
int temp;
// swapping in cyclic order
temp = *n2;
*n2 = *n1;
*n1 = *n3;
*n3 = temp;
}
54
Largest Element
Find the Largest Element
#include
#include
int main() {
int n;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
// Allocating memory for n elements
data = (double *)calloc(n, sizeof(double));
if (data == NULL) {
printf("Error!!! memory not allocated.");
exit(0);
}
// Storing numbers entered by the user.
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}
// Finding the largest number
for (int i = 1; i < n; ++i) {
if (*data < *(data + i)) {
*data = *(data + i);
}
}
55
smallest Element
Find the Largest Element
#include
#include
int main() {
int n;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
// Allocating memory for n elements
data = (double *)calloc(n, sizeof(double));
if (data == NULL) {
printf("Error!!! memory not allocated.");
exit(0);
}
// Storing numbers entered by the user.
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}
// Finding the largest number
for (int i = 1; i < n; ++i) {
if (*data < *(data + i)) {
*data = *(data + i);
}
}
printf("Largest number = %.2lf", *data);
free(data);
return 0;
}
56
Frequency of a Character
Find the Frequency of a Character
#include
int main() {
char str[1000], ch;
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to find its frequency: ");
scanf("%c", &ch);
for (int i = 0; str[i] != '\0'; ++i) {
if (ch == str[i])
++count;
}
printf("Frequency of %c = %d", ch, count);
return 0;
}
57
count vowels, consonants, etc.
count vowels, consonants, etc.
#include
int main() {
char line[150];
int vowels, consonant, digit, space;
// initialize all variables to 0
vowels = consonant = digit = space = 0;
// get full line of string input
printf("Enter a line of string: ");
fgets(line, sizeof(line), stdin);
// loop through each character of the string
for (int i = 0; line[i] != '\0'; ++i) {
// convert character to lowercase
line[i] = tolower(line[i]);
// check if the character is a vowel
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u') {
// increment value of vowels by 1
++vowels;
}
// if it is not a vowel and if it is an alphabet, it is a consonant
else if ((line[i] >= 'a' && line[i] <= 'z')) {
++consonant;
}
// check if the character is a digit
else if (line[i] >= '0' && line[i] <= '9') {
++digit;
}
// check if the character is an empty space
else if (line[i] == ' ') {
++space;
}
}
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}
58
Remove Characters in String Except Alphabets
Remove Characters in String Except Alphabets
#include
int main() {
char line[150];
printf("Enter a string: ");
fgets(line, sizeof(line), stdin); // take input
for (int i = 0, j; line[i] != '\0'; ++i) {
// enter the loop if the character is not an alphabet
// and not the null character
while (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] == '\0')) {
for (j = i; line[j] != '\0'; ++j) {
// if jth element of line is not an alphabet,
// assign the value of (j+1)th element to the jth element
line[j] = line[j + 1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}
59
Calculate Length of String
Calculate Length of String without Using strlen() Function
#include
int main() {
char s[] = "Programming is fun";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
return 0;
}
60
Concatenate Two Strings
Concatenate Two Strings Without Using strcat()
#include
int main() {
char s1[100] = "programming ", s2[] = "is awesome";
int length, j;
// store length of s1 in the length variable
length = 0;
while (s1[length] != '\0') {
++length;
}
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}
// terminating the s1 string
s1[length] = '\0';
printf("After concatenation: ");
puts(s1);
return 0;
}
61
Sort strings in the dictionary order
Sort strings in the dictionary order
#include
#include
int main() {
char str[5][50], temp[50];
printf("Enter 5 words: ");
// Getting strings input
for (int i = 0; i < 5; ++i) {
fgets(str[i], sizeof(str[i]), stdin);
}
// storing strings in the lexicographical order
for (int i = 0; i < 5; ++i) {
for (int j = i + 1; j < 5; ++j) {
// swapping strings if they are not in the lexicographical order
if (strcmp(str[i], str[j]) > 0) {
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
printf("\nIn the lexicographical order: \n");
for (int i = 0; i < 5; ++i) {
fputs(str[i], stdout);
}
return 0;
}
62
Store Information and Display
Store Information and Display it Using Structure
#include
struct student {
char name[50];
int roll;
float marks;
} s;
int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
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;
}