C- Program Basic
1.C Hello World Program
// Header file for input output functions
#include <stdio.h>
// Main function: entry point for execution
int main() {
// Writing print statement to print hello world
printf("Hello World");
return 0;
}
2.C Program to Print Your Own Name
// C Program to Print Your Own Name using printf
#include <stdio.h>
int main() {
// Printing your name "Rahul" on the output screen
printf("Rahul");
return 0;
3.C Program to Print an Integer Entered By
the User
// C Program to Print
// Integer value
#include <stdio.h>
// Driver code
int main()
{
// Declaring integer
int x = 5;
// Printing values
printf("Printing Integer value %d", x);
return 0;
}
4.C Program to Add Two Numbers
// C program to add two numbers
#include <stdio.h>
int main() {
int a, b, sum = 0;
// Read two numbers from the user
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
// Calculate the addition of a and b
// using '+' operator
sum = a + b;
printf("Sum: %d", sum);
return 0;
}
5.C Program to Check Whether a Number is
Prime or Not
#include <stdbool.h>
#include <stdio.h>
int main() {
int n = 29;
int cnt = 0;
// If number is less than/equal to 1,
// it is not prime
if (n <= 1)
printf("%d is NOT prime", n);
else {
// Count the all divisors of
// given number
for (int i = 1; i <= n; i++) {
// Check n is divided by
// i or not
if (n % i == 0)
cnt++;
}
// If n is divisible by more than 2 numbers
// then it is not prime
if (cnt > 2)
printf("%d is NOT prime", n);
// else it is prime
else
printf("%d is prime", n);
}
return 0;
}
6.C Program to Multiply two Floating-Point
Numbers
// C program to multiply two
// floating point numbers
#include <stdio.h>
// Function to multiply floating point
// numbers
float multiply(float a, float b)
{
return a * b;
}
// Driver code
int main()
{
float A = 2.12, B = 3.88, product;
// Calling product function
product = multiply(A, B);
// Displaying result up to 3 decimal places.
printf("Product of entered numbers is:%.3f", product);
return 0;
}
7.C Program to Print the ASCII Value of a
Character
// C program to print ASCII Value of Character using
// implicit conversion with format specifier.
#include <stdio.h>
int main() {
char c = 'k';
// %d displays the integer value of
// a character
// %c displays the actual character
printf("The ASCII value of %c is %d", c, c);
return 0;
}
8.C Program to Swap Two Numbers
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
// Swapping values of a and b
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
return 0;
}
9.C Program to Calculate Fahrenheit to
Celsius
// C Program to convert
// Fahrenheit to Celsius
#include <stdio.h>
// Function to convert Degree
// Fahrenheit to Degree Celsius
float fahrenheit_to_celsius(float f)
{
return ((f - 32.0) * 5.0 / 9.0);
}
// Driver code
int main()
{
float f = 40;
// Passing parameter to function
printf("Temperature in Degree Celsius : %0.2f",
fahrenheit_to_celsius(f));
return 0;
}
10. C Program to Find the Size of int, float,
double, and char
// C Program to Find the Size of int, float, double, and
// char using sizeof operator directly
#include <stdio.h>
int main() {
// Determine and Print the size of int
printf("Size of int: %u bytes\n", sizeof(int));
// Determine and Print the size of float
printf("Size of float: %u bytes\n", sizeof(float));
// Determine and Print the size of double
printf("Size of double: %u bytes\n", sizeof(double));
// Determine and Print the size of char
printf("Size of char: %u bytes\n", sizeof(char));
return 0;
}
11. C Program to Add Two Complex Numbers
// C program to demonstrate
// addition of complex numbers
#include <stdio.h>
// define a structure for complex number
typedef struct complexNumber {
int real;
int img;
} complex;
// This function accepts two complex numbers
// as parameter and return addition of
// them.
complex add(complex x, complex y);
// Driver code
int main()
{
// Define three complex type numbers
complex a, b, sum;
// First complex number
[Link] = 2;
[Link] = 3;
// Second complex number
[Link] = 4;
[Link] = 5;
// Print first complex number
printf("\n a = %d + %di", [Link], [Link]);
// print second complex number
printf("\n b = %d + %di", [Link], [Link]);
// call add(a,b) function and
// pass complex numbers a & b
// as an parameter.
sum = add(a, b);
// Print result
printf("\n sum = %d + %di", [Link], [Link]);
return 0;
}
// Complex add(complex x, complex y)
// function definition
complex add(complex x, complex y)
{
// Define a new complex number.
complex add;
// Add real part of a&b
[Link] = [Link] + [Link];
// Add Imaginary part of a&b
[Link] = [Link] + [Link];
return (add);
}
12. C Program to Print Prime Numbers From
1 to N
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
// This function is to check
// if a given number is prime
bool isPrime(int n)
{
// 0 and 1 are not prime numbers
if (n == 1 || n == 0)
return false;
// Check for divisibility from 2 to sqrt(n)
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
// Driver code
int main()
{
int N = 50;
// Check every number from 1 to N
for (int i = 1; i <= N; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
return 0;
}
13. C Program to Find Simple Interest
// C program to find the simple interest
#include <stdio.h>
int main() {
// Input values
float P = 1, R = 1, T = 1;
// Calculate simple interest
float SI = (P * T * R) / 100;
// Print Simple Interest
printf("Simple Interest = %f\n", SI);
return 0;
}
14. C Program to Find Compound Interest
// C program to calculate Compound Interest
#include <stdio.h>
// For using pow function we must
// include math.h
#include<math.h>
// Driver code
int main()
{
// Principal amount
double principal = 10000;
// Annual rate of interest
double rate = 5;
// Time
double time = 2;
// Calculating compound Interest
double Amount = principal *
((pow((1 + rate / 100),
time)));
double CI = Amount - principal;
printf("Compound Interest is : %lf",CI);
return 0;
}
15. C Program for Area And Perimeter Of
Rectangle
Method-1
// C program to demonstrate the
// area and perimeter of rectangle
#include <stdio.h>
int main()
{
int l = 10, b = 10;
printf("Area of rectangle is : %d", l * b);
printf("\nPerimeter of rectangle is : %d", 2 * (l + b));
return 0;
}
Method-2
// C program to demonstrate the
// area and perimeter of rectangle
#include <stdio.h>
int main()
{
int l = 10, b = 10;
int A, P;
A = l * b;
P = 2 * (l + b);
printf("Area of rectangle is : %d", A);
printf("\nPerimeter of rectangle is : %d", P);
return 0;
}
Method-3
// C program to demonstrate the
// area and perimeter of rectangle
// using function
#include <stdio.h>
int area(int a, int b)
{
int A;
A = a * b;
return A;
}
int perimeter(int a, int b)
{
int P;
P = 2 * (a + b);
return P;
}
int main()
{
int l = 10, b = 10;
printf("Area of rectangle is : %d", area(l, b));
printf("\nPerimeter of rectangle is : %d",
perimeter(l, b));
return 0;
}
C Program-Control Flow
16 C Program to check a Number is Positive or
Negative or Zero
// C Program to check if a number is positive, negative,
// or zero using simple conditional checks
#include <stdio.h>
void checkNum(int N) {
// Check if the number is zero
if (N == 0) {
printf("Zeri\n");
}
// Check if the number is less than zero
else if (N < 0) {
printf("Negative\n");
}
// If neither, the number is positive
else {
printf("Positive\n");
}
}
int main() {
int N = 10;
checkNum(N);
return 0;
}
17 C Program to check for Odd or Even Number
// C Program to Check Even or Odd Using Modulo Operator
#include <stdio.h>
void checkOddEven(int N) {
// Find the remainder
int r = N % 2;
// Condition for even
if (r == 0) {
printf("Even");
}
// Condition for odd number
else {
printf("Odd");
}
}
int main() {
int N = 101;
checkOddEven(N);
return 0;
}
18 C Program to check Vowel or Consonant
// C program to check if a character
// is a vowel or consonant
#include <stdio.h>
// Driver code
int main()
{
char ch = 'A';
// Checking if the character ch
// is a vowel or not.
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E'
|| ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O'
|| ch == 'u' || ch == 'U') {
printf("The character %c is a vowel.\n", ch);
}
else {
printf("The character %c is a consonant.\n", ch);
}
return 0;
}
19C program to find the largest number among three
numbers
// C program to find the largest number among three number
// using nested if-else
#include <stdio.h>
int main()
{
int c = 10, b = 22, a = 9;
// Finding largest by comparing using relational operators
if (a >= b) {
if (a >= c)
printf("%d is the largest number.", a);
else
printf("%d is the largest number.", c);
}
else {
if (b >= c)
printf("%d is the largest number.", b);
else
printf("%d is the largest number.", c);
}
return 0;
}
20C Program to Calculate Sum of Natural Numbers
(1) Using while loop
// C Program to demonstrate
// Sum of Natural Numbers
// using while loops
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
i = 1;
// while loop executes
// the statements until the
// condition is false
while (i <= n) {
// adding natural numbers
// up to given number n
s += i;
i++;
}
// printing the result
printf("Sum = %d", s);
return 0;
}
(2) Using for loop
// C Program to demonstrate
// Sum of Natural Numbers
// using for loops
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
for (i = 0; i <= n; i++) {
// adding natural numbers
// up to given number n
s += i;
}
// printing the result
printf("Sum = %d", s);
return 0;
}
(3) Using recursion
// C Program to demonstrate
// Sum of Natural Numbers
// using recursion
#include <stdio.h>
int sumofnaturalnumbers(int num)
{
if (num != 0)
// adding natural numbers up to given number n
return num + sumofnaturalnumbers(num - 1);
else
return num;
}
int main()
{
int number = 10;
// printing the result
printf("Sum = %d", sumofnaturalnumbers(number));
return 0;
}
(4) Using functions
// C Program to demonstrate
// Sum of Natural Numbers
// using functions
#include <stdio.h>
int sumofnaturalnumbers(int num)
{
int i, s = 0;
for (i = 0; i <= num; i++) {
// adding natural numbers
// up to given number n
s += i;
}
// printing the result
printf("Sum = %d", s);
}
int main()
{
int number = 10;
// calling the function
sumofnaturalnumbers(number);
return 0;
}
(5) Using formula sum of n natural numbers =n*(n+1)/2
// C Program to demonstrate
// Sum of Natural Numbers
#include <stdio.h>
int main()
{
int num = 10;
int s,x;
s=num*(num+1);
x=(int)(s/2);
printf("Sum = %d", x);
return 0;
}
21Program to print alphabets from A to Z using loop
// C Program to display alphabets using ASCII values
#include <stdio.h>
int main()
{
int i;
printf("Alphabets from (A-Z) are:\n");
// ASCII value of A=65 and Z=90
for (i = 65; i <= 90; i++) {
// Integer i with %c will be converted to character
// before printing.%c will takes its equivalent
// character value
printf("%c ", i);
}
printf("\nAlphabets from (a-z) are:\n");
// ASCII value of a=97 and z=122
for (i = 97; i <= 122; i++) {
// Integer i with %c will be converted to character
// before printing.%c will takes its equivalent
// character value
printf("%c ", i);
}
return 0;
}
22C Program to check leap year
// C program to check if a given
// year is leap year or not
#include <stdbool.h>
#include <stdio.h>
bool checkYear(int year)
{
// If a year is multiple of 400,
// then it is a leap year
if (year % 400 == 0)
return true;
// Else If a year is multiple of 100,
// then it is not a leap year
else if (year % 100 == 0)
return false;
// Else If a year is multiple of 4,
// then it is a leap year
else if (year % 4 == 0)
return true;
// if no above condition is satisfied, then it is not
// a leap year
return false;
}
// Driver code
int main()
{
int year = 2000;
if (checkYear(year)) {
printf("Leap Year");
}
else {
printf("Not a Leap Year");
}
return 0;
}
23C Program to find factorial of a number
#include <stdio.h>
unsigned int factorial(unsigned int N) {
int fact = 1, i;
// Loop from 1 to N to get the factorial
for (i = 1; i <= N; i++) {
fact *= i;
}
return fact;
}
int main() {
int N = 5;
int fact = factorial(N);
printf("Factorial of %d is %d", N, fact);
return 0;
}
24C Program make a simple calculator
// C Program to make a Simple Calculator using
// switch-case statements
#include <stdio.h>
#include <float.h>
int main() {
char op;
double a, b, res;
// Read the operator
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
// Read the two numbers
printf("Enter two operands: ");
scanf("%lf %lf", &a, &b);
// Define all four operations in the corresponding
// switch-case
switch (op) {
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '*':
res = a * b;
break;
case '/':
res = a / b;
break;
default:
printf("Error! Incorrect Operator Value\n");
res = -DBL_MAX;
}
if(res!=-DBL_MAX)
printf("%.2lf", res);
return 0;
}
25C Program to generate multiplication table
// C program to Demonstrate the
// Multiplication table of a number
#include <stdio.h>
void print_table(int range, int num)
{
// Declaring a variable mul to store the product.
int mul;
// For loop to calculate the Multiplication table.
for (int i = 1; i <= range; i++) {
// To store the product.
mul = num * i;
// Printing the Multiplication Table.
printf("%d * %d = %d", num, i, mul);
// Proceeding to the next line.
printf("\n");
}
}
// Driver code
int main()
{
// The range of the
// Multiplication table
int range = 10;
// The number to calculate the
// Multiplication table
int num = 5;
// Calling the Function.
print_table(range, num);
return 0;
}
26C Program to print Fibonacci Series
// C Program to print the fibonacci series using loops
#include <stdio.h>
void printFib(int n) {
// If the number of terms is smaller than 1
if (n < 1) {
printf("Invalid Number of terms\n");
return;
}
// First two terms of the series
int prev1 = 1;
int prev2 = 0;
// for loop that prints n terms of fibonacci series
for (int i = 1; i <= n; i++) {
// Print current term and update previous terms
if (i > 2) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
printf("%d ", curr);
}
else if (i == 1)
printf("%d ", prev2);
else if (i == 2)
printf("%d ", prev1);
}
}
int main() {
int n = 9;
// Printing first n fibonacci terms
printFib(n);
return 0;
}
27C Program to find LCM of two numbers
// C program to find LCM of
// two numbers
#include <stdio.h>
// Driver code
int main()
{
int x = 15, y = 25, max;
max = (x > y) ? x : y;
// While loop to check if max variable
// is divisible by x and y
while (1) {
if (max % x == 0 && max % y == 0) {
printf("The LCM of %d and %d is %d.", x, y,
max);
break;
}
++max;
}
return 0;
}
28C Program to check Armstrong Number
#include <math.h>
#include <stdio.h>
#include <stdbool.h>
bool isArmstrong(int N) {
int temp = N;
int sum = 0;
// Get the number of digits
// Adding 1 to compensate for the loss of fraction part
// of the value returned by log10 due to the conversion
// into integer
int K = log10(temp) + 1;
// Calculate the sum of the digits raised to the power of
// num_digits
while (temp > 0) {
int digit = temp % 10;
sum += pow(digit, K);
temp /= 10;
}
// Return whether the sum is equal to the original number or not
return (sum == N);
}
int main() {
int N = 153;
// Check if the number is an Armstrong number
if (isArmstrong(N)) {
printf("Yes, %d is an Armstrong Number\n", N);
}
else {
printf("No, %d is not an Armstrong Number\n", N);
}
return 0;
}
29 C Program to display armstrong numbers between
1 to 1000
Approach 1
// C Program to Display Armstrong
// numbers between 1 to 1000
#include <math.h>
#include <stdio.h>
int main()
{
int i, sum, num, count = 0;
printf(
"All Armstrong number between 1 and 1000 are:\n");
// This loop will run for 1 to 1000
for (i = 1; i <= 1000; i++) {
num = i;
// Count number of digits.
while (num != 0) {
num /= 10;
count++;
}
num = i;
sum = pow(num % 10, count)
+ pow((num % 100 - num % 10) / 10, count)
+ pow((num % 1000 - num % 100) / 100, count);
// Check for Armstrong Number
if (sum == i) {
printf("%d ", i);
}
count = 0;
}
}
Approach 2
// C Program to Display Armstrong
// numbers between 1 to 1000
#include <stdio.h>
#include <math.h>
int main()
{
int i, digit1, digit2, digit3, sum, num;
printf("All Armstrong number between 1 and 1000 are:\n");
// This loop will run for 1 to 1000
for (i = 1; i <= 1000; i++)
{
num = i;
// All single digit numbers are Armstrong number.
if (num <= 9)
{
printf("%d ", num);
}
else
{
sum = pow(num % 10, 3) + pow((num % 100 - num % 10) / 10,
3) + pow((num % 1000 - num % 100) / 100, 3);
if (sum == i)
{
printf("%d ", i);
}
}
}
}
30C Program to display Armstrong numbers
between two intervals
#include <stdio.h>
// Function to count the number of digits in a number
int countDigits(int num) {
int count = 0;
while (num != 0) {
num /= 10;
++count;
}
return count;
}
// Function to compute the power of a number manually
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; ++i) {
result *= base;
}
return result;
}
// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
int originalNum = num;
int n = countDigits(num);
int result = 0;
while (num != 0) {
int remainder = num % 10;
result += power(remainder, n);
num /= 10;
}
return (result == originalNum);
}
int main() {
int low = 100, high = 500; // Define the range in the driver code
printf("Armstrong numbers between %d and %d are: ", low, high);
// Iterate through each number in the interval
for (int i = low + 1; i < high; ++i) {
if (isArmstrong(i)) {
printf("%d ", i);
}
}
return 0;
}
31C Program to reverse a number
#include <stdio.h>
// Iterative function to
// reverse digits of num
int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
int main()
{
int num = 4562;
printf("Given number: %d\n", num);
printf("Revers of the number: %d",
reverseDigits(num));
getchar();
return 0;
}
32C Program to check whether a number is
Palindrome or not
#include <stdio.h>
int reverseNum(int N) {
// Function to store the reversed number
int rev = 0;
while (N > 0) {
// Extract the last digit
int dig = N % 10;
// Append the digit to the reversed number
rev = rev * 10 + dig;
// Remove the last digit
N /= 10;
}
return rev;
}
int isPalindrome(int N) {
// Negative numbers are not palindromes
if (N < 0)
return 0;
return N == reverseNum(N);
}
int main() {
int N = 121;
if (isPalindrome(N)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
33C Program to Check whether a number is Prime or
Not
#include <stdbool.h>
#include <stdio.h>
int main() {
int n = 29;
int cnt = 0;
// If number is less than/equal to 1,
// it is not prime
if (n <= 1)
printf("%d is NOT prime", n);
else {
// Count the all divisors of
// given number
for (int i = 1; i <= n; i++) {
// Check n is divided by
// i or not
if (n % i == 0)
cnt++;
}
// If n is divisible by more than 2 numbers
// then it is not prime
if (cnt > 2)
printf("%d is NOT prime", n);
// else it is prime
else
printf("%d is prime", n);
}
return 0;
}
34 C Program - Pattern Printing
1. C Program to Print Pyramid Pattern
#include <stdio.h>
int main() {
int n = 5;
// Outer loop for printing rows
for (int i = 0; i< n; i++) {
// Inner loop for printing * in each rows
for (int j = 0; j <= i; j++)
printf("* ");
printf("\n");
}
return 0;
}
35.C Program to Print Given Triangle
// C program to print a triangle
#include <stdio.h>
// Driver code
int main()
{
int n = 6;
// ith row has i elements
for (int i = 1; i<= n; i++) {
for (int j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
36.C Program For Printing Inverted Pyramid
#include <stdio.h>
int main() {
int n = 5;
// Outer loop to print all rows
for (int i = 0; i< n; i++) {
// Inner loop to print the * in each row
for (int j = 0; j < n - i; j++)
printf("* ");
printf("\n");
}
}
37.C Program to Print Number Pattern
#include <stdio.h>
int main() {
int n = 5;
// Outer loop to iterate through each row
for (int i = 0; i< n; i++) {
// First inner loop to print white spaces
for (int j = 0; j < n - i - 1; j++)
printf(" ");
// Second inner loop to print number in each row
for (int k = 0; k < n; k++)
printf("%d ", k + 1);
printf("\n");
}
return 0;
}
38.C Program To Print Character Pyramid Pattern
#include <stdio.h>
int main() {
int n = 5;
// Outer loop for printing rows
for (int i = 1; i<= n; i++) {
// Inner loop for printing alphabets in each row
for (int j = 1; j <= i; j++) {
printf("%c ", 'A' + j - 1);
}
printf("\n");
}
return 0;
}
39.C Program to Print Continuous Character Pattern
// C program to print continuous
// character pattern using
// character
#include <stdio.h>
int main()
{
int i, j;
// Number of rows
int rows = 3;
// Taking first character of alphabet
// which is useful to print pattern
char character = 'A';
// This loop is used to identify
// number rows
for (i = 0; i< rows; i++)
{
// This for loop is used to
// identify number of columns
// based on the rows
for (j = 0; j <= i; j++)
{
// Printing character to get
// the required pattern
printf("%c ",character);
// Incrementing character value so
// that it will print the next character
character++;
}
printf("\n");
}
return 0;
}
40.C Program To Print Hollow Pyramid Patterns
#include <stdio.h>
int main() {
int n = 5;
// Outer loop to print each row
for (int i = 1; i<= n; i++) {
// Inner loop to print the whitespace and stars
for (int j = 1; j <= i; j++) {
// Print '*' for first or last column, or last row
// print whitespaces for the rest
if (j == 1 || j == i || i == n)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
41.C Program To Print Inverted Hollow Pyramid
Patterns
#include <stdio.h>
int main() {
int n = 5;
// Loop for printing each row
for (int i = 0; i< n; i++) {
// Inner loop for prinitng stars * and whitespaces
for (int j = 0; j < n - i; j++) {
if (j == 0 || j == n - i - 1 || i == 0)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
42.C Program To Print Hollow Diamond Pattern
#include <stdio.h>
int main() {
int n = 5;
// First outer loop to iterator through each row
for (int i = 0; i< 2 * n - 1; i++) {
// Assigning values to the comparator according to
// the row number
int comp;
if (i< n) comp = 2 * (n - i) - 1;
else comp = 2 * (i - n + 1) + 1;
// First inner loop to print leading whitespaces
for (int j = 0; j < comp; j++)
printf(" ");
// Second inner loop to print star * and inner
// whitespaces
for (int k = 0; k < 2 * n - comp; k++) {
if (k == 0 || k == 2 * n - comp - 1)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
43.C Program To Print Diamond Pattern
#include <stdio.h>
int main() {
int n = 5;
// First outer loop to iterator through each row
for (int i = 0; i< 2 * n - 1; i++) {
// Assigning values to the comparator according to
// the row number
int comp;
if (i< n) comp = 2 * (n - i) - 1;
else comp = 2 * (i - n + 1) + 1;
// First inner loop to print leading whitespaces
for (int j = 0; j < comp; j++)
printf(" ");
// Second inner loop to print stars *
for (int k = 0; k < 2 * n - comp; k++) {
printf("* ");
}
printf("\n");
}
return 0;
}
[Link] Triangle Program in C
#include <stdio.h>
int main() {
int n = 5;
// Outer loop to print each row
for (int i = 0; i< n; i++) {
// Print leading spaces for alignment
for (int j = 0; j < n - i - 1; j++)
printf(" ");
// Print values in row
int val = 1;
for (int k = 0; k <= i; k++) {
printf("%d ", val);
// Calculate the next value in the row
val = val * (i - k) / (k + 1);
}
printf("\n");
}
return 0;
}
45.C Program to Print Floyd's Triangle Pyramid
Patterns
#include <stdio.h>
int main() {
int n = 5;
int c = 1;
// Outer loop to print all rows
for (int i = 0; i< n; i++) {
// Inner loop to print number in each row
for (int j = 0; j <= i; j++) {
printf("%d ", c++);
}
printf("\n");
}
return 0;
}
46.C Program To Print Reverse Floyd's Pattern
#include <stdio.h>
int main() {
int n = 4;
int c = n * (n + 1) / 2;
// Outer loop to print rows
for (int i = n; i>= 1; i--) {
// Inner loop to print the numbers in each row
for (int j = 1; j <= i; j++)
printf("%d ", c--);
printf("\n");
}
return 0;
}
C Program - Functions
47 .C Program To Check Prime Number By Creating a
Function
// C Program to Check Prime Number using Simple Trial
// Division Approach
#include <stdio.h>
int isPrime(int N) {
// Check divisibility from 2 to N-1
for (int i = 2; i< N; i++) {
// If N is divisible by i, it is not a prime number
if (N % i == 0) {
return 0;
}
}
// If no divisors were found, N is a prime number
return 1;
}
int main() {
int N = 10;
printf("Is %d prime?\n", N);
// Check if the number is prime
if (isPrime(N)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
48 .C Program to Display Prime Numbers Between Two
Intervals Using Functions
// C Program to demonstrate Prime Numbers
// Between Two Intervals Using for
// loop in a function
#include <stdio.h>
// User-defined function to check
// prime number
int checkPrimeNumber(int number)
{
int i, f = 1;
// Condition for finding the
// prime numbers between the
// given intervals
for (i = 2; i<= number / 2; ++i)
{
if (number % i == 0)
{
f = 0;
break;
}
}
return f;
}
// Driver code
int main()
{
int num1 = 2, num2 = 10, j, f;
printf("Prime numbers between %d and %d are: ",
num1, num2);
for (j = num1; j < num2; ++j)
{
// if flag is equal to 1 then
// it is a prime number
// calling the function
f = checkPrimeNumber(j);
if (f == 1)
{
// Printing the result
printf("%d ", j);
}
}
return 0;
}
49.C Program for Quadratic Equation Roots
// C program to find roots of
// a quadratic equation
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Prints roots of quadratic
// equation ax*2 + bx + x
void findRoots(int a, int b, int c)
{
// If a is 0, then equation is
// not quadratic, but linear
if (a == 0) {
printf("Invalid");
return;
}
int d = b * b - 4 * a * c;
double sqrt_val = sqrt(abs(d));
if (d > 0) {
printf("Roots are real and different\n");
printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),
(double)(-b - sqrt_val) / (2 * a));
}
else if (d == 0) {
printf("Roots are real and same\n");
printf("%f", -(double)b / (2 * a));
}
else // d < 0
{
printf("Roots are complex\n");
printf("%f + i%f\n%f - i%f", -(double)b / (2 * a),
sqrt_val / (2 * a), -(double)b / (2 * a),
sqrt_val / (2 * a));
}
}
// Driver code
int main()
{
int a = 1, b = -7, c = 12;
// Function call
findRoots(a, b, c);
return 0;
}
50.C Program to Check Whether a Number Can Be
Express as Sum of Two Prime Numbers
// C program to check whether a
// number can be expressed as sum
// of two prime numbers
#include <stdio.h>
// Function to check prime number
int isPrime(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;
}
// Driver code
int main()
{
int n = 7, i, flag = 0;
for (i = 2; i<= n / 2; ++i) {
// condition for i to be a
// prime number
if (isPrime(i) == 1) {
// condition for n-i to
// be a prime number
if (isPrime(n - i) == 1) {
printf("Yes\n");
return 0;
}
}
}
printf("No\n");
return 0;
}
51.C Program to Find Sum of Natural Numbers using
Recursion
// C program to find the sum of n
// natural numbers using recursion
#include <stdio.h>
// Returns the sum of first n
// natural numbers
int recSum(int n)
{
// Base condition
if (n <= 1)
return n;
// Recursive call
return n + recSum(n - 1);
}
// Driver code
int main()
{
int n = 10;
printf("Sum = %d ", recSum(n));
return 0;
}
[Link] Program in C
#include <stdio.h>
unsigned int factorial(unsigned int N) {
int fact = 1, i;
// Loop from 1 to N to get the factorial
for (i = 1; i<= N; i++) {
fact *= i;
}
return fact;
}
int main() {
int N = 5;
int fact = factorial(N);
printf("Factorial of %d is %d", N, fact);
return 0;
}
[Link] Common Divisor (GCD)of Two Numbers
in C
// C program to find GCD of two numbers
#include <math.h>
#include <stdio.h>
// Function to return gcd of a and b
int gcd(int a, int b)
{
// Find Minimum of a and b
int result = ((a < b) ?a : b);
while (result > 0) {
// Check if both a and b are divisible by result
if (a % result == 0 && b % result == 0) {
break;
}
result--;
}
// return gcd of a nd b
return result;
}
// Driver program to test above function
int main()
{
int a = 98, b = 56;
printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
return 0;
}
// This code is contributed by Suruchi Kumari
54. C Program to Reverse a Stack using Recursion
// C program to reverse a
// stack using recursion
#include <stdio.h>
#include <stdlib.h>
#define bool int
// structure of a stack node
struct sNode {
char data;
struct sNode* next;
};
// Function Prototypes
void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
bool isEmpty(struct sNode* top);
void print(struct sNode* top);
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
void insertAtBottom(struct sNode** top_ref, int item)
{
if (isEmpty(*top_ref))
push(top_ref, item);
else {
// Hold all items in Function Call
// Stack until we reach end of the
// stack. When the stack becomes
// empty, the isEmpty(*top_ref)becomes
// true, the above if part is executed
// and the item is inserted at the bottom
int temp = pop(top_ref);
insertAtBottom(top_ref, item);
// Once the item is inserted
// at the bottom, push all
// the items held in Function
// Call Stack
push(top_ref, temp);
}
}
// Below is the function that
// reverses the given stack using
// insertAtBottom()
void reverse(struct sNode** top_ref)
{
if (!isEmpty(*top_ref)) {
// Hold all items in Function
// Call Stack until we
// reach end of the stack
int temp = pop(top_ref);
reverse(top_ref);
// Insert all the items (held in
// Function Call Stack)
// one by one from the bottom
// to top. Every item is
// inserted at the bottom
insertAtBottom(top_ref, temp);
}
}
// Driver Code
int main()
{
struct sNode* s = NULL;
push(&s, 4);
push(&s, 3);
push(&s, 2);
push(&s, 1);
printf("
Original Stack ");
print(s);
reverse(&s);
printf("
Reversed Stack ");
print(s);
return 0;
}
// Function to check if
// the stack is empty
bool isEmpty(struct sNode* top)
{
return (top == NULL) ?1 : 0;
}
// Function to push an item to stack
void push(struct sNode** top_ref, int new_data)
{
// allocate node
struct sNode* new_node
= (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow
");
exit(0);
}
// put in the data
new_node->data = new_data;
// link the old list
// off the new node
new_node->next = (*top_ref);
// move the head to
// point to the new node
(*top_ref) = new_node;
}
// Function to pop an item from stack
int pop(struct sNode** top_ref)
{
char res;
struct sNode* top;
// If stack is empty then error
if (*top_ref == NULL) {
printf("Stack overflow
");
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
// Function to print a
// linked list
void print(struct sNode* top)
{
printf("
");
while (top != NULL) {
printf(" %d ", top->data);
top = top->next;
}
}
[Link] of a Number in C
// C program for the above approach
#include <stdio.h>
// Naive iterative solution to
// calculate pow(x, n)
long power(int x, unsigned n)
{
// Initialize result to 1
long long pow = 1;
// Multiply x for n times
for (int i = 0; i< n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
int main(void)
{
int x = 2;
unsigned n = 3;
// Function call
int result = power(x, n);
printf("%d", result);
return 0;
}
55.C Program to Print a 2D Array
#include <stdio.h>
// Funtion that takes 2d array as parameter
void print(int arr[3][3], int n, int m) {
for (int i = 0; i< n; i++) {
for (int j = 0; j < m; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
}
int main() {
int arr[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
// Passing the array along with the
// size of rows and columns
print(arr, 3, 3);
return 0;
}
56.C Program to Find Largest Element in an Array
#include <stdio.h>
int findMax(int arr[], int n) {
// Assume the first element is the largest
int max = arr[0];
for (int i = 1; i< n; i++) {
// Update max if arr[i] is greater
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {5, 2, 7, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", findMax(arr, n));
return 0;
}
57.C Program For Maximum and Minimum of an
Array
/* structure is used to return two values from minMax() */
#include<stdio.h>
struct pair
{
int min;
int max;
};
struct pair getMinMax(int arr[], int n)
{
struct pair minmax;
int i;
/*If there is only one element then return it as min and max both*/
if (n == 1)
{
[Link] = arr[0];
[Link] = arr[0];
return minmax;
}
/* If there are more than one elements, then initialize min
and max*/
if (arr[0] >arr[1])
{
[Link] = arr[0];
[Link] = arr[1];
}
else
{
[Link] = arr[1];
[Link] = arr[0];
}
for (i = 2; i<n; i++)
{
if (arr[i] >[Link])
[Link] = arr[i];
else if (arr[i] <[Link])
[Link] = arr[i];
}
return minmax;
}
/* Driver program to test above function */
int main()
{
int arr[] = {1000, 11, 445, 1, 330, 3000};
int arr_size = 6;
struct pair minmax = getMinMax (arr, arr_size);
printf("nMinimum element is %d", [Link]);
printf("nMaximum element is %d", [Link]);
getchar();
58.C Program for Binary Search
// C Program to implement binary search using iteration
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key) {
// Loop will run till left > right. It means that there
// are no elements to consider in the given subarray
while (left <= right) {
// calculating mid point
int mid = left + (right - left) / 2;
// Check if key is present at mid
if (arr[mid] == key) {
return mid;
}
// If key greater than arr[mid], ignore left half
if (arr[mid] < key) {
left = mid + 1;
}
// If key is smaller than or equal to arr[mid],
// ignore right half
else {
right = mid - 1;
}
}
// If we reach here, then element was not present
return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);
// Element to be searched
int key = 23;
int result = binarySearch(arr, 0, size - 1, key);
if (result == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", result);
}
return 0;
}
59.C Program to Calculate Average of an Array
#include <stdio.h>
float getAvg(int arr[], int n) {
int sum = 0;
// Find the sum of all elements
for (int i = 0; i< n; i++) {
sum += arr[i];
}
// Return the average
return (float)sum / n;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Calculate the average of array arr
float res = getAvg(arr, n);
printf("%.2f\n", res);
return 0;
}
60.C Program for Selection Sort
// C program for implementation of selection sort
#include <stdio.h>
void selectionSort(int arr[], int N) {
// Start with the whole array as unsored and one by
// one move boundary of unsorted subarray towards right
for (int i = 0; i< N - 1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] <arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first
// element in the unsorted part
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int N = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
for (int i = 0; i< N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Calling selection sort
selectionSort(arr, N);
printf("Sorted array: \n");
for (int i = 0; i< N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
61. C Program For Insertion Sort
// C program to implement insertion sort
#include <math.h>
#include <stdio.h>
void insertionSort(int arr[], int N) {
// Starting from the second element
for (int i = 1; i< N; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are
// greater than key, to one position to
// the right of their current position
while (j >= 0 &&arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Move the key to its correct position
arr[j + 1] = key;
}
}
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
for (int i = 0; i< N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Calling insertion sort on array arr
insertionSort(arr, N);
printf("Sorted array: ");
for (int i = 0; i< N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
62.C Program to Sort the Elements of an Array in
Descending Order
#include <stdio.h>
#include <stdlib.h>
// Comparator function to sort in descending order
int comp(const void *a, const void *b) {
return (*(int*)b - *(int*)a);
}
int main() {
int arr[] = {1, 3, 5, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
// Sorting the array using qsort
qsort(arr, n, sizeof(int), comp);
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
return 0;
}
63.C Program to Sort an Array in Ascending Order
#include <stdio.h>
#include <stdlib.h>
// Custom comparator
int comp(const void* a, const void* b) {
// If a is smaller, positive value will be returned
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = { 2 ,6, 1, 5, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Sort the array using qsort
qsort(arr, n, sizeof(int), comp);
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
return 0;
}
64.C Program to Remove Duplicates from Sorted Array
#include <stdio.h>
int removeDup(int arr[], int n) {
if (n == 0) return 0;
int j = 0;
for (int i = 1; i< n - 1; i++) {
// If a unique element is found, place
// it at arr[j + 1]
if (arr[i] != arr[j])
arr[++j] = arr[i];
}
// Return the new ending of arr that only
// contains unique elements
return j + 1;
}
int main() {
int arr[] = {1, 1, 2, 2, 3, 4, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Remove duplicates
n = removeDup(arr, n);
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
return 0;
}
65.C Program To Merge Two Arrays
// C program to merge two arrays into a new array using
// memcpy()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int* mergeArrays(int arr1[], int n1, int arr2[], int n2) {
// Resultant array to store merged array
int *res = (int*)malloc(sizeof(int) * n1 * n2);
// Copy elements of the first array
memcpy(res, arr1, n1 * sizeof(int));
// Copy elements of the second array
memcpy(res + n1, arr2, n2 * sizeof(int));
return res;
}
int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
// Merge arr1 and arr2
int* res = mergeArrays(arr1, n1, arr2, n2);
for (int i = 0; i< n1 + n2; i++)
printf("%d ", res[i]);
return 0;
}
66.C Program to Remove All Occurrences of an
Element in an Array
// C Program to remove All Occurrences of
// an element in an array using functions
#include <stdio.h>
// function declaration
int remove_element(int* array, int n, int val)
{
int i;
// iterates array elements
for (i = 0; i< n; i++)
// if the given array element is not equal to given
// value then print array element
if (array[i] != val)
printf("%d ", array[i]);
}
int main()
{
int array[6] = { 1, 2, 1, 3, 1 }, size = 5, value = 1;
remove_element(array, size, value);
}
67.C Program to Find Common Array Elements
Between Two Arrays
// C Program to demonstrate scrunity of
// 2 Common Array Elements Using Brute force
#include <stdio.h>
int main()
{
int array1[] = { 8, 2, 3, 4, 5, 6, 7, 1 };
int array2[] = { 4, 5, 7, 11, 6, 1 };
int i, j, flag, x, k = 0;
int result[100];
printf("Common elements are: ");
// To traverse in array1.
for (i = 0; i<sizeof(array1) / 4; i++) {
// To traverse in array2.
for (j = 0; j <sizeof(array2) / 4; j++) {
// To match elements of array1 with elements of
// array2.
if (array1[i] == array2[j]) {
flag = 0;
// To traverse in result array.
for (x = 0; x < k; x++) {
// Check whether found element is
// already present in result array or
// not.
if (result[x] == array1[i]) {
flag++;
}
}
// If we found a new element which is common
// in both arrays then store it in result
// array and print it.
if (flag == 0) {
result[k] = array1[i];
printf("%d ", result[k]);
k++;
}
}
}
}
}
68.C Program to Copy an Array to Another Array
#include <stdio.h>
#include <string.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int n = sizeof(arr1) / sizeof(arr1[0]);
int arr2[n];
// Use memcpy to copy arr1 to arr2
memcpy(arr2, arr1, n * sizeof(arr1[0]));
for (int i = 0; i< n; i++)
printf("%d ", arr2[i]);
return 0;
}
69.C Program for Program for array rotation
// C++ program to illustrate how to rotate array
#include <stdio.h>
// Function to rotate array left by one position
void leftRotateByOne(int arr[], int n)
{
int temp = arr[0];
for (int i = 0; i< n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = temp;
}
// Function to rotate array left by d positions
void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i< d; i++) {
leftRotateByOne(arr, n);
}
}
// Function to print an array
void printArray(int arr[], int n)
{
for (int i = 0; i< n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int d = 2;
// Rotate array left by d positions
leftRotate(arr, d, n);
printf("Array after rotated by %d positions is: ", d);
printArray(arr, n);
return 0;
}