C Program to Convert Octal to Binary.

Given an octal number as input, write a C program to convert it to its equivalent binary representation.

Example:
Input: 52
Output: 101010

Input: 55
Output: 101101

  • Octal Number: An octal number is expressed in the base-8 numeral system, which uses the digits from 0 to 7.
  • Binary Number: A binary number is a number expressed in the base-2 numeral system, which uses only two symbols: 0 and 1.

C program to convert an Octal to a Binary Number.

//C code implementation to convert octal to binary
#include <stdio.h>

// Function to convert octal digit to binary
char* octalToBinary(char digit) {
    switch (digit) {
        case '0': return "000";
        case '1': return "001";
        case '2': return "010";
        case '3': return "011";
        case '4': return "100";
        case '5': return "101";
        case '6': return "110";
        case '7': return "111";
        default: return "";
    }
}

int main() {
    char octal[20];
    printf("Enter an octal number: ");
    scanf("%s", octal);

    // Convert octal to binary
    char binary[60] = "";
    for (int i = 0; octal[i] != '\0'; i++) {
        char* binaryDigit = octalToBinary(octal[i]);
        strcat(binary, binaryDigit);
    }

    printf("Binary Equivalent: %s", binary);

    return 0;
}
Output:
Enter an octal number: 63
Binary Equivalent: 110011

Time Complexity: O(n)
Space Complexity: O(n)

C Program to Convert Binary to Octal.

Given a binary number as input, write a C program to convert it to its equivalent octal representation. 

Example:

Input: 10100
Output: 24

Input: 11011
Output: 33

Before moving to the code section, let us learn about Binary and Octal numbers:
  • Binary Number: A binary number is expressed in the base-2 numeral system, which uses only two symbols: 0 and 1.
  • Octal Number: An octal number is expressed in the base-8 numeral system, which uses the digits from 0 to 7.


Step-by-step approach:

Step 1: Obtain the binary number as input.
Step 2: Convert the binary number to its decimal equivalent by iterating through each digit and multiplying it by 2 raised to a power.
Step 3: Convert the decimal number to its octal representation by dividing it by 8 repeatedly and storing the remainder.
Step 4: Print the resulting octal representation of the binary number.

C program to convert a Binary Number to Octal Number.

//C code implementation of converting Binary to Octal
#include <stdio.h>

int main() {
    long long binary, decimal = 0;
    int power = 0;

    printf("Enter a binary number: ");
    scanf("%lld", &binary);

    // Convert binary to decimal
    while (binary != 0) {
        int digit = binary % 10;
        decimal += digit * (1 << power);
        power++;
        binary /= 10;
    }

    // Convert decimal to octal
    int octalNum[100], i = 0;
    while (decimal != 0) {
        octalNum[i] = decimal % 8;
        decimal /= 8;
        i++;
    }

    printf("Octal Equivalent: ");
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", octalNum[j]);
    }

    return 0;
}
Output:
Enter a binary number: 11010
Octal Equivalent: 32

Time Complexity: The time taken to convert from binary to decimal is O(log₂ N) and the time taken to convert decimal to octal is O(log₂ N) so the overall time complexity is O(log₂ N + log₈ N).

Space Complexity: The space complexity of the code is O(log N) because we need to store the decimal equivalent of the binary number, and the number of digits in the decimal number is log N.

C Program to Generate Multiplication Table.

A multiplication table, also known as a times table, is a mathematical table used to define a multiplication operation for an algebraic system. In the context of basic arithmetic, a multiplication table shows the results of multiplying two numbers from 1 to a specific value. 

Example:

Multiplication Table of 4:
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40


Problem Statement.

Write a C program to generate any multiplication table for a given number (up to a specified limit) and display the table in a formatted manner.


Steps to Generate the Multiplication Table:

Step 1: Input the number for which you want to generate the multiplication table (let's call it 'num').

Step 2: Input the limit up to which you want to generate the table (let's call it 'limit').

Step 3: Use a loop to iterate from 1 to 'limit'.

Step 4: Inside the loop, calculate the product of 'num' and the loop variable and display the result in a formatted manner.


C Program to Generate Multiplication Table of Any Number.

//C program to print multiplication table of a number
#include <stdio.h>

int main() {
    int num, limit;

    printf("Enter the number for multiplication table: ");
    scanf("%d", &num);

    printf("Enter the limit for the table: ");
    scanf("%d", &limit);

    //Generate and display the table
    printf("Multiplication table for %d up to %d:\n", num, limit);
    for (int i = 1; i <= limit; i++) {
        printf("%d x %d = %d\n", num, i, num * i);
    }

    return 0;
}
Output:
Enter the number for multiplication table: 6
Enter the limit for the table: 10
Multiplication table for 6 up to 10:
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60

This program generates the multiplication table for the given number (5 in this case) up to the specified limit (10 in this case) and displays the results in a formatted manner. 

Similar articles:

C Program to Create a Calculator using Switch Statement.

In this C programming tutorial, we are going to learn how to create a simple calculator to perform simple arithmetic calculations like +, - x, and /  between two operands given by the user. Here we are going to use the switch statement to create our basic calculator.


Calculator using Switch statement in C program.

//C calculator using switch statement
#include <stdio.h>

int main() {
    char operator;
    double num1, num2, result;

    // Input the operator and two numbers
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);

    printf("Enter two numbers: ");
    scanf("%lf %lf", &num1, &num2);

    // Perform the calculation based on the operator
    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("Result: %lf\n", result);
            break;
        case '-':
            result = num1 - num2;
            printf("Result: %lf\n", result);
            break;
        case '*':
            result = num1 * num2;
            printf("Result: %lf\n", result);
            break;
        case '/':
            result = num1 / num2;
            printf("Result: %lf\n", result);
            break;
        default:
            printf("Error: Invalid operator.\n");
    }

    return 0;
}
Output:
Enter an operator (+, -, *, /): +
Enter two numbers: 23 12
Result: 35.000000
Output:
Enter an operator (+, -, *, /): %
Enter two numbers: 23 43
ERROR!
Error: Invalid operator.

Explanation:
In this program, the user is prompted to enter an operator (+, -, *, /) and two numbers. Then, using the switch statement, the program performs the corresponding calculation based on the operator.

Program to Count Subarrays with K Odd Numbers.

Given an integer array containing n elements and an integer value k, we need to write a program to count the number of continuous subarrays in the given array that contain k number of odd numbers. 

Example:
Input: arr[] = {3, 1, 2, 1, 1}, k = 3
Output: 2
Explanation:
Subarrays with 3 odd numbers are {3, 1, 2, 1} and {1, 2, 1, 1}. 

Input: arr[] = {2, 1, 9, 3, 1}, k = 2
Output: 4
Explanation:
Subarrays with 2 odd numbers are 
{1, 9} {9, 3} {3, 1} {2, 1, 9} 

This problem can be solved by multiple approaches, let's discuss each of them one by one with efficiency.

Approach 1: Brute Force.

The brute force approach involves considering all possible subarrays of the given array and checking each subarray to see if it contains exactly k odd numbers.

Below is the C++ code implementation for this approach.
//C++ code to Count Subarrays with K Odd Numbers.
//Brute force
#include<iostream>
#include <vector>
using namespace std;

//function to return count of subarrays
//with k odd numbers
int countOddSubarrays(vector<int>& nums, int k) {
    int n = nums.size();
    int count = 0;
    
    //traverse for all possible subarrays
    for (int i = 0; i < n; i++) {
        int oddCount = 0;
        for (int j = i; j < n; j++) {
            if (nums[j] % 2 == 1) {
                oddCount++;
            }
            if (oddCount == k) {
                count++;
            }
        }
    }

    return count;
}

int main(){
    vector<int> nums = {1, 2, 1, 1, 4, 1};
    int k = 3;

    cout << countOddSubarrays(nums, k);
}
Output:
4

Time Complexity: O(n^2), because we are using the nested loop to check all possible subarrays.
Space Complexity: O(1), as it does not use any extra space to solve this problem.

Approach 2: Sliding Window Approach.

In this approach, we begin by initializing two pointers, start and end, both pointing to the first element of the array. Additionally, we set count and ans to zero. 

The next step involves traversing the array using the end pointer. During this traversal, we increment the count variable if the element is odd. We then slide the window to the right until the count becomes equal to k.

With each step, we update the ans variable to keep track of the number of subarrays containing exactly k odd integers. Eventually, we return the value of ans.

To calculate the number of subarrays with exactly k odd integers, we compute the difference between the number of subarrays with less than k odd integers and the number of subarrays with at most k-1 odd integers. Remarkably, we can leverage the same subArray function to compute both of these values efficiently.

Below is the C++ code implementation for the above approach.
//C++ code to Count Subarrays with K Odd Numbers.
//Sliding window approach
#include<iostream>
#include <vector>
using namespace std;

int subArray(vector<int>& nums, int k) {
    int count = 0, ans = 0, start = 0, end = 0;
    int n = nums.size();

    // Sliding window approach
    while(end<n){
        if(nums[end]%2==1){
            count++;
        }
        // Shrink the window until the count 
        //becomes less than or equal to K
        while(count>k){
            if(nums[start]%2==1){
                count--;
            }
            start++;
        }
        ans += end-start+1;
        end++;
    }
    return ans;
}
// Function to count the number of 
//subarrays with K odd numbers
int countOddSubarrays(vector<int>& nums, int k) {
    /*
    difference between number of subarrays with at most k-1
    odd elements with number of subarrays with at most k
    odd elements
    */
    return subArray(nums, k) - subArray(nums, k - 1);
}

int main(){
    vector<int> nums = {2, 1, 9, 3, 1};
    int k = 2;

    cout << countOddSubarrays(nums, k);
}
Output:
4

Time Complexity: O(n)
Space Complexity: O(1)

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.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson