Program to Reverse a Number in C.

Given an integer number num containing n digits, we need to write a C program to reverse the given number.

Example:
Input: num = 1234
Output: 4321

Input: num = 45910
Output: 1954

To reverse a number, we need to extract each digit of the given number from right to left and then construct the reversed number by adding the digits in the reverse order.

Algorithm to Reverse a Number.

Below are the steps to follow:
Step 1: Take an integer num as input from the user.
Step 2: Initialize a variable reversedNum to 0.
Step 3: Repeat the following steps until num becomes 0:
  • Extract the last digit of num using num % 10 and store it in a variable remainder.
  • Append the remainder to the reversedNum by multiplying reversedNum by 10 and adding the remainder.
  • Remove the last digit from num by dividing it by 10.
Step 4: The final value of reversedNum is the reversed number. 

Program to Reverse an Integer.

Below is the C code implementation of the above algorithm to reverse any integer number.
//C program to reverse a number
#include <stdio.h>

int main() {
    int num, reversedNum = 0, remainder;

    printf("Enter an integer: ");
    scanf("%d", &num);

    while (num != 0) {
        // Extract the last digit
        remainder = num % 10; 
        // Append the digit to the reversed number
        reversedNum = reversedNum * 10 + remainder; 
        // Remove the last digit
        num /= 10; 
    }

    printf("Reversed number: %d\n", reversedNum);

    return 0;
}
Output:
Enter an integer: 1246
Reversed number: 6421

Time Complexity: O(log n) where n is the input number. 
Space Complexity: O(1) as a constant amount of space is required to solve this problem.

C Program to Find GCD for two numbers. (Euclidean Algorithm)

In this C programming tutorial, we will learn multiple approaches to finding the GCD for two numbers. But before learning those approaches let us understand what is GCD?


What is GCD (Greatest Common Divisor)?

The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the given integers without leaving a remainder. It is also known as the Greatest Common Factor (GCF) or Highest Common Divisor (HCD).

Example:

Let's find the GCD of two numbers, 36 and 48.

The divisors of 36 are: 1, 2, 3, 4, 6, 9, 12, 18, 36.
The divisors of 48 are: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48.

The common divisors of 36 and 48 are: 1, 2, 3, 4, 6, 12.

Among the common divisors, the greatest one is 12. 
Therefore, GCD(36, 48) = 12.

There are multiple approaches to finding GCD in C programming and here we are going to learn below three approaches: 

Approach 1: Euclidean Algorithm.

This is the most commonly used method for finding the GCD of two numbers. It involves successive division of the larger number by the smaller number until the remainder becomes zero.

Here is an example of how the Euclidean Algorithm work:

Example: Find the GCD of 36 and 48.

Step 1: Divide the larger number by the smaller number and find the remainder.
48 ÷ 36 = 1 remainder 12

Step 2: Now, replace the larger number with the smaller number, and the smaller number with the remainder from Step 1.
New larger number = 36
New smaller number = 12

Step 3: Repeat the process until the remainder becomes zero.
36 ÷ 12 = 3 remainder 0

Step 4: Since the remainder is now zero, we stop. The GCD is the last non-zero remainder obtained in Step 3, which is 12.

Below is the C program implementation of the Euclidean Algorithm to find the GCD of two numbers.
//C program to find gcd using Euclidean Algorithm
#include <stdio.h>

//function to find gcd
int gcd(int a, int b) {
    int temp;
    while (b != 0) {
        temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int num1, num2;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);

    int result = gcd(num1, num2);

    printf("The GCD of %d and %d is %d.\n", num1, num2, result);
    return 0;
}
Output:
Enter two positive integers: 36 48
The GCD of 36 and 48 is 12.

Time Complexity: O(log(min(a, b))), where 'a' and 'b' are the two input numbers.
Space Complexity: O(1) as a constant amount of space is required to solve this problem.

Approach 2: Brute Force.

In this approach, we find all the divisors of both numbers and then find their common divisors to determine the GCD.

Below is the C program to calculate the GCD of two numbers using for loop.
//C code to find gcd of two numbers using for loop
#include <stdio.h>

// Function to calculate (GCD) of two numbers
int gcd(int a, int b) {
    // Find the smaller of the two numbers
    int smaller = (a < b) ? a : b; 
    int result = 1; 

    // Iterate from 1 to the smaller number
    for (int i = 1; i <= smaller; i++) {
        // Check if 'i' is a common divisor of both 'a' and 'b'
        if (a % i == 0 && b % i == 0) {
            result = i; 
        }
    }

    return result; 
}

int main() {
    int num1, num2;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);

    int result = gcd(num1, num2); 

    printf("The GCD of %d and %d is %d.\n", num1, num2, result);
    return 0;
}
Output:
Enter two positive integers: 46 68
The GCD of 46 and 68 is 2.

Time Complexity: O(n), where n is the minimum of the two input numbers. 
Space Complexity: O(1), as a constant amount of space is required to solve this problem.

Approach 3: Using Recursion.

It is the recursive version of the Euclidean Algorithm, where the GCD of two numbers is recursively calculated as the GCD of the smaller number and the remainder of the larger number divided by the smaller number.

Example: Find GCD of 48 and 36.
GCD(36, 48) = GCD(48, 36 mod 48) = GCD(48, 12)
GCD(48, 12) = GCD(12, 48 mod 12) = GCD(12, 0)

Since the remainder becomes zero in the second step, the GCD is the last non-zero remainder, which is 12. Therefore, the GCD of 36 and 48 is 12.

Below is the recursive C program to find GCD for two numbers.
//C code to find gcd of two numbers using recursion
#include <stdio.h>

//recursive function
int gcd(int a, int b) {
    //base case
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

int main() {
    int num1, num2;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);

    int result = gcd(num1, num2);

    printf("The GCD of %d and %d is %d.\n", num1, num2, result);
    return 0;
}
Output:
Enter two positive integers: 60 24
The GCD of 60 and 24 is 12.

Time Complexity: O(log(min(a, b))), where 'a' and 'b' are the two input numbers. The time complexity is determined by the number of recursive calls required to reach the base case.
Space Complexity: O(log(min(a, b))), because each recursive call creates a new activation record (stack frame) to store the function's local variables and return address.

C Program to Check an Armstrong Number.

In this C programming tutorial, we are going to learn how to check if the given number is an Armstrong number or not. But before moving to the code section let us first understand what is an Armstrong number?


Armstrong Numbers.

An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in the number. Let's try to understand this with an example.

Example:

Input: 371
Output: Armstrong Number.

Explanation: 
Total number of digits = 3
= 3^3 + 7^3 + 1^3
= 3*3*3 + 7*7*7 + 1*1*1
= 27 + 343 + 1
= 371

C Program to check Three Digits, Armstrong Numbers.

//C code to check three digit armstrong number
#include <stdio.h>
#include <math.h>

int main() {
    int num, originalNum, remainder, result = 0;

    printf("Enter a three-digit number: ");
    scanf("%d", &num);

    if (num < 100 || num > 999) {
        printf("Invalid input.\n");
        return 0;
    }

    originalNum = num;

    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, 3);
        originalNum /= 10;
    }

    if (result == num) {
        printf("%d is an Armstrong number.\n", num);
    } else {
        printf("%d is not an Armstrong number.\n", num);
    }

    return 0;
}
Output:
Enter a three-digit number: 153
153 is an Armstrong number.

C Program to check n digits Armstrong Number.

//C code to check armstrong number of n digits
#include <stdio.h>
#include <math.h>

int main() {
    int num, originalNum, remainder, result = 0, n = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    originalNum = num;

    // Count the number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        ++n;
    }

    originalNum = num;

    // Calculate the result
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    // Check if the number is Armstrong
    if (result == num) {
        printf("%d is an Armstrong number.\n", num);
    } else {
        printf("%d is not an Armstrong number.\n", num);
    }

    return 0;
}
Output:
Enter an integer: 1634
1634 is an Armstrong number.

Time Complexity: The time complexity of the above C program to check if a number is an Armstrong number is O(d), where 'd' is the number of digits in the input number.

Space Complexity: The space complexity of the program is O(1), which means it uses constant space.

C Program to Print Fibonacci Series.

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The series is represented as 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. In other words, each number in the series (after the first two numbers) is the sum of the two preceding ones.


In this article, we are going to print the Fibonacci series using C programming.

Algorithm to Print Fibonacci Series.

  • Input the number of terms 'n' from the user.
  • Initialize variables 'first' and 'second' as 0 and 1, respectively, representing the first two numbers of the series.
  • Print the first two numbers of the series, i.e., 0 and 1.
  • Use a loop to calculate and print the subsequent terms of the series.
  • In each iteration, calculate the next term as the sum of the 'first' and 'second'.
  • Update 'first' to the value of 'second' and 'second' to the value of the newly calculated term.
  • Repeat steps 4 to 6 'n-2' times, as the first two numbers are already printed. 

Below is the C program to display Fibonacci Series.

//c program for fibonacci sequqence.
#include <stdio.h>

int main() {
    int n, first = 0, second = 1, next;

    printf("Enter the number of terms in the Fibonacci series: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    // Print the first two terms
    printf("%d, %d", first, second);

    // Calculate and print the subsequent terms
    for (int i = 2; i < n; i++) {
        next = first + second;
        printf(", %d", next);

        // Update first and second for the next iteration
        first = second;
        second = next;
    }

    printf("\n");
    return 0;
}
Output:
Enter the number of terms in the Fibonacci series: 7
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8

Time Complexity: The time complexity of the given C program to print the Fibonacci series is O(n), where 'n' is the number of terms in the series.

Space Complexity: The space complexity of the program is O(1), which means it uses constant space. 

C Program to Print Sum of Natural Numbers.

In this C programming, we are going to calculate the sum of n natural numbers using different methods. Before moving to the code part, let's first understand natural numbers.


What are Natural Numbers?

Natural numbers are a set of positive whole numbers starting from 1 and extending indefinitely, including 1, 2, 3, 4, and so on. They do not include zero or any negative numbers. 

Example:

Input: n = 10
Output: 55

Explanation: 
1 + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Below are four different approaches we are going to use to find the sum of natural numbers:

Sum of Natural Numbers using while Loop.

In this approach we are using a while loop, we take input n from the user and calculate the sum of natural numbers from 1 to n.

C Code:
//C program to sum natural numbers using while loop
#include <stdio.h>

int main() {
    int n, sum = 0, i = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    while (i <= n) {
        sum += i;
        i++;
    }

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 8
Sum of natural numbers from 1 to 8 is 36.

Time Complexity: O(n) as the while loop run n times.
Space Complexity: O(1) no extra space is required.

Sum of Natural Numbers using for Loop.

In this approach we are using a for loop, we follow the same process but use a for loop to iterate from 1 to n.

C Code:
//C program to find sum of natural numbers using for loop
#include <stdio.h>

int main() {
    int n, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 11
Sum of natural numbers from 1 to 11 is 66.

Time Complexity: O(n) as the for loop runs n times.
Space Complexity: O(1) no extra space is required.

Sum of Natural Numbers using Recursion.

In this approach we are using recursion, we define a function sumRecursion that takes n as input. The function calculates the sum of natural numbers from 1 to n using recursion. The base case is when n becomes 0, and the function returns 0. Otherwise, it returns n + sumRecursion(n - 1).

C Code:
//C program to find the sum of natural numbers using Recursion
#include <stdio.h>

//recursive function
int sumFunction(int n) {
    int sum = 0;

    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

int main() {
    int n, sum;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    sum = sumFunction(n);

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 12
Sum of natural numbers from 1 to 12 is 78.

Time Complexity: O(n) as the recursive function is called n+1 times.
Space Complexity: O(n) as we require extra stack space for a recursive function.

C Program to Check Given Year is Leap Year.

In this C program, we are going to check whether the given year is a leap year or not. But before writing code for this we first need to understand what is Leap Year? A leap year is a year that contains an extra day, February 29, making it 366 days instead of the usual 365 days. 


What is Leap Year?

Leap years occur once in four years to keep the calendar year synchronized with the astronomical year, which is approximately 365.2422 days long. Usually, a non-leap year contains 28 days in the month of February but a leap year contains 29 days in the month of February. 


Below are a few rules to check if the given year is a leap year or not:

  • The year must be evenly divisible by 4.
  • If the year is divisible by 100, it must also be divisible by 400.
Example:

Input: 2008
Output: 2008 is a Leap Year

Explanation: 
  • Check if the year is divisible by 4: 2008 % 4 = 0.
  • Since 2008 is divisible by 4, proceed to the next step.
  • Check if the year is divisible by 100: 2008 % 100 = 8.
  • 2008 is not divisible by 100, so not necessary to check its divisibility by 400.
  • Since 2008 is divisible by 4 and not by 100, it is a leap year.

Algorithm to Check Leap Year:

Step 1: Input the year from the user.
Step 2: Check if the year is evenly divisible by 4.
Step 3: If it is not divisible by 4, it is not a leap year.
Step 4: If it is divisible by 4, check if it is also divisible by 100.
Step 5: If it is divisible by 100, check if it is also divisible by 400.
Step 6: If it is divisible by 400, it is a leap year.
Step 7: If it is divisible by 100 but not by 400, it is not a leap year.
Step 8: If it is divisible by 4 and not by 100, it is a leap year.

C Code:
Below is the C program to check whether the year is a leap year or not:

//C program implementation to check leap year
#include <stdio.h>

int main() {
    int year;

    printf("Enter a year: ");
    scanf("%d", &year);
    
    //check leap year conditions
    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                printf("%d is a leap year.\n", year);
            } else {
                printf("%d is not a leap year.\n", year);
            }
        } else {
            printf("%d is a leap year.\n", year);
        }
    } else {
        printf("%d is not a leap year.\n", year);
    }

    return 0;
}
Output:
Enter a year: 2024
2024 is a leap year.

C Program to Count Vowels and Consonants.

Write a C program to count the number of vowels and consonants in a given string. Vowels are the letters 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase), while consonants are all other letters of the alphabet.

Example:
Input: School
Output: Number of Vowels = 2
        Number of consonants = 4

Input: Programming
Output: Number of Vowels = 3
        Number of consonants = 8 

Vowel: A vowel is a type of speech sound produced by the vocal cords without any significant constriction or closure of the air passage. In the English alphabet, the letters 'a', 'e', 'i', 'o', and 'u' are considered vowels. (alert-success)
Consonant: A consonant is a speech sound in which the air is at least partially obstructed and does not flow freely through the vocal cords. In the English alphabet, all letters except 'a', 'e', 'i', 'o', and 'u' are considered consonants. (alert-success)


Step-by-step Algorithm.

Step 1: Input the string from the user.
Step 2: Initialize variables to store the counts of vowels and consonants, initially set to 0.
Step 3: Traverse each character of the string.
Step 4: Check if the character is an alphabet (a-z, A-Z).
Step 5: If the character is a vowel (either lowercase or uppercase), increment the vowel count.
Step 6: If the character is a consonant (neither a vowel nor a space), increment the consonant count.
Step 7: Display the final counts of vowels and consonants.


C code to count the number of vowels and consonants in the given string.

//C program to count vowels and consonants
#include <stdio.h>
#include <ctype.h>

int main() {
    char str[100];
    int vowels = 0, consonants = 0, i = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    while (str[i] != '\0') {
        // Convert character to lowercase
        char ch = tolower(str[i]); 

        // Check if the character is an alphabet
        if ((ch >= 'a' && ch <= 'z')) {
            // character is a vowel, increment the vowel count
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowels++;
            } else {
                // character is a consonant, increment the consonant count
                consonants++;
            }
        }
        i++;
    }

    printf("Number of vowels: %d\n", vowels);
    printf("Number of consonants: %d\n", consonants);

    return 0;
}
Output:
Enter a string: Good Life
Number of vowels: 4
Number of consonants: 4

Time Complexity: O(n) where n is the number of character the string contain.
Space Complexity: O(1) as no extra space is required to solve this problem.
Note: In the above code, we have used tolower() built-in function which is a part of ctype.h header file. It is used to convert characters to lowercase equivalents. (alert-passed) 

C Program to Check Whether the Number is Even or Odd.

In this C program, we will determine whether a given number is even or odd. An even number is an integer that is exactly divisible by 2 without leaving a remainder, while an odd number is an integer that leaves a remainder of 1 when divided by 2. 

For Example:
2, 4, 6, 8, 10, etc are Even numbers.
1, 3, 7, 11, 13, etc are Odd numbers.

Steps to Check Whether a Number is Even or Odd:

Step 1: Take an Input number from the user.
Step 2: Use the modulo operator (%) to check if the number leaves a remainder of 0 when divided by 2.
Step 3: If the remainder is 0, the number is even. Otherwise, it is odd.
Step 4: Display the result indicating whether the number is even or odd.

C Program to check Even or Odd.

//C program to check even or odd number
#include <stdio.h>

int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

    // Check if number is even or odd using the modulo operator
    if (number % 2 == 0) {
        // remainder is 0, the number is even
        printf("%d is an even number.\n", number);
    } else {
        // remainder is 1, the number is odd
        printf("%d is an odd number.\n", number);
    }

    return 0;
}
Output:
Enter an integer: 10
10 is an even number.

In the above example code, the user enters an integer number, and then our program checks if the number is divisible by two or not. If the number is perfectly divisible by 2 then we say that the given number is Even else we say the given number is Odd.

C Program to Find Greatest Number Among Three.

Given three numbers a, b, and c. Your task is to write a C program to find the largest number among three given numbers. The program should take three integer inputs from the user and determine which number is the largest among them.

Example:

Input: a = 10, b = 5, c = 9
Output: Largest Number = 10

Input: a = -5, b = 2, c = 1
Output: Largest Number = 2

Steps to Find the Greatest Number Among Three:

Step 1: Input three numbers (num1, num2, num3) from the user.
Step 2: Compare the three numbers to find the greatest among them.
Step 3: Display the greatest number as the result.

C code to find the Greatest number using if-else.
//C program to find the greatest number among three
#include <stdio.h>

int main() {
    int a, b, c, greatest;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a > b && a > c) {
        greatest = a;
    } else if (b > a && b > c) {
        greatest = b;
    } else {
        greatest = c;
    }

    printf("The greatest number among three is: %d\n", greatest);

    return 0;
}
Output:
Enter three numbers: 3 6 1
The greatest number among three is: 6


C Code to find the greatest number among three using Ternary Operator.
//C program to find the greatest number using ternary operator
#include <stdio.h>

int main() {
    int a, b, c, greatest;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    // ternary operator to find greatest
    greatest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

    printf("The greatest number is: %d\n", greatest);

    return 0;
}
Output:
Enter three numbers: 10 20 40
The greatest number is: 40

Explanation:

To find the greatest number among three given numbers, we compare the numbers in pairs. We first compare num1 and num2, then num1 and num3, and finally num2 and num3. The number that is greater than the other two in each comparison is the greatest number among the three.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo