C Program to Convert Octal to Decimal.

In this C program tutorial, we are going to learn how to convert an Octal to a Decimal number. Let's understand the process with an example. 

Step-by-step Algorithm:

Step 1: Input the octal number from the user.
Step 2: Initialize the decimalNum variable to 0, and base variable to 1. The decimalNum will store the final decimal equivalent, and the base is used to keep track of the current place value (powers of 8).
Step 3: Convert octal to decimal using a while loop. In each iteration, we extract the last digit (remainder) of the octal number using the modulus operator %. Then, we multiply the digit with the current base value and add it to the decimalNum. We update the octalNum by removing the last digit (integer division by 10) and increasing the base by multiplying it by 8, which represents the next place value (8 raised to the power of the current position).
Step 4: Output the decimal equivalent of the octal number.

C Code:

//C program to Convert Octal to Decimal.
#include <stdio.h>

int main() {
    int octalNum, decimalNum = 0, base = 1, remainder;

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

    // Convert octal to decimal
    while (octalNum != 0) {
        // Extract the last digit
        remainder = octalNum % 10; 
        // Multiply digit with base and add to decimalNum
        decimalNum += remainder * base;
        // Remove the last digit
        octalNum /= 10; 
        // Increase base by a power of 8 for next digit
        base *= 8; 
    }

    printf("Decimal equivalent: %d\n", decimalNum);

    return 0;
}
Output:
Enter an octal number: 127
Decimal equivalent: 87

Time Complexity: O(log N)
Space Complexity: O(1)

How To Create a Sticky Header on Scroll?

A sticky header is a popular web design technique that keeps the header fixed at the top of the page, even as users scroll down the content. This provides a seamless user experience, making it easier for visitors to access important navigation options without having to scroll back to the top of the page. 

Here are steps that you can follow to Create a Sticky Header for your Webpage:


Step 1: Add the necessary HTML section.

To create a sticky header, we first need to set up the HTML structure. The header element typically contains the website logo, navigation menu, and other crucial elements. We can use the <header> tag to enclose these elements and ensure it's placed at the top of the <body> element.

HTML Code:

<!DOCTYPE html>
<html>
  <head>
    <title>Sticky Header Example</title>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Services</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </nav>
    </header>

    <main>
      <h1>Welcome to Our Website</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non
        sapien vitae elit blandit bibendum a eu metus.
      </p>
      <!-- Add more content here -->
    </main>

    <footer>
      <p>&copy; 2023 Your Website. All rights reserved.</p>
    </footer>
  </body>
</html>

Step 2: Add the necessary CSS Style to fix the header on Scroll.

To make the header stick to the top of the page, we'll use CSS positioning. We can set the header's position to "fixed" to ensure it remains fixed relative to the viewport while users scroll down.

CSS Code:
header {
    position: fixed;
    top: 0;
    width: 100%;
    background-color: #ffffff;
    /* Add other styles such as height, 
    padding, and box-shadow as per your design */
}

If you want more control over the sticky header behavior, JavaScript can be used to add or remove the "sticky" class dynamically based on the user's scrolling behavior.

Javascript Code:
<script>
window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (window.scrollY > 0) {
        header.classList.add('sticky');
    } else {
        header.classList.remove('sticky');
    }
});
</script>

Below is the complete working example of a Sticky Header:
<!DOCTYPE html>
<html>
  <head>
    <title>Sticky Header Example</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        font-family: Arial, sans-serif;
      }

      header {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        background-color: #333;
        padding: 10px 20px;
        color: #fff;
      }

      nav ul {
        list-style: none;
        margin: 0;
        padding: 0;
      }

      nav li {
        display: inline-block;
        margin-right: 20px;
      }

      nav li a {
        text-decoration: none;
        color: #fff;
        font-size: 18px;
      }

      main {
        padding: 100px 20px;
        text-align: center;
      }

      h1 {
        font-size: 36px;
        margin-bottom: 20px;
      }

      footer {
        text-align: center;
        background-color: #333;
        color: #fff;
        padding: 10px;
      }

      /* Sticky header styles */
      header.sticky {
        position: fixed;
        top: 0;
      }
    </style>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Services</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </nav>
    </header>

    <main>
      <h1>Welcome to Our Website</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non
        sapien vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit
        amet, consectetur adipiscing elit. Phasellus non sapien vitae elit
        blandit bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur
        adipiscing elit. Phasellus non sapien vitae elit blandit bibendum a eu
        metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Phasellus non sapien vitae elit blandit bibendum a eu metus. Lorem ipsum
        dolor sit amet, consectetur adipiscing elit. Phasellus non sapien vitae
        elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
        consectetur adipiscing elit. Phasellus non sapien vitae elit blandit
        bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing
        elit. Phasellus non sapien vitae elit blandit bibendum a eu metus. Lorem
        ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non sapien
        vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
        consectetur adipiscing elit.
      </p>
      <h3>Coding is Great</h3>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non
      sapien vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Phasellus non sapien vitae elit blandit
      bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing
      elit. Phasellus non sapien vitae elit blandit bibendum a eu metus. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non sapien
      vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Phasellus non sapien vitae elit blandit
      bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing
      elit. Phasellus non sapien vitae elit blandit bibendum a eu metus. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non sapien
      vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Phasellus non sapien vitae elit blandit
      bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing
      elit. Phasellus non sapien vitae elit blandit bibendum a eu metus. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non sapien
      vitae elit blandit bibendum a eu metus. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Phasellus non sapien vitae elit blandit
      bibendum a eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing
      elit.
    </main>

    <footer>
      <p>&copy; 2023 Your Website. All rights reserved.</p>
    </footer>
  </body>
  <script>
    // JavaScript to make the header sticky
    window.addEventListener("scroll", function () {
      const header = document.querySelector("header");
      if (window.scrollY > 0) {
        header.classList.add("sticky");
      } else {
        header.classList.remove("sticky");
      }
    });
  </script>
</html>
Output:
Sticky Header Example

Pro-Tip: For simple cases, where you need the header to stick only during a certain scroll range, the CSS position: sticky property can be used.

CSS Code:

header {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    width: 100%;
    background-color: #ffffff;
    /* Add other styles as per your design */
}

C Program to Convert Binary to Decimal.

Write a C program to convert a binary number to its decimal equivalent. 
Let's understand the processing of converting a binary number to a decimal number with one example.

Example: 
Input: binaryNum = 10101
Output: 22

Explanation:
remainder = 10101 % 10 = 1, 
decimal = 1 * 1 = 1, base = 1 * 2 = 2, 
binaryNum = 1010

remainder = 1010 % 10 = 0, 
decimal = 0 * 2 + 1 * 2 = 2, base = 2 * 2 = 4, 
binaryNum = 101

remainder = 101 % 10 = 1, 
decimal = 1 * 4 + 2 * 1 = 6, base = 4 * 2 = 8, 
binaryNum = 10

remainder = 10 % 10 = 0, 
decimal = 0 * 8 + 6 * 1 = 6, base = 8 * 2 = 16, 
binaryNum = 1

remainder = 1 % 10 = 1, 
decimal = 1 * 16 + 6 * 1 = 22, base = 16 * 2 = 32, 
binaryNum = 0

Decimal equivalent = 22

Steps-by-step Algorithm:

Step 1: Take input of a binary number from the user.
Step 2: Initialize a variable decimal to store the decimal equivalent, initially set to 0.
Step 3: Initialize a variable base to store the current place value, initially set to 1.
Step 4: Extract the rightmost digit of the binary number using the modulo operator %.
Step 5: Multiply the extracted digit by base and add it to the decimal variable.
Step 6: Divide the binary number by 10 to remove the rightmost digit.
Step 7: Update the base value by multiplying it by 2, as we are moving to the next higher place value (binary is base-2 system).
Step 8: Repeat steps 4 to 7 until the binary number becomes 0.
Step 9: The value of the decimal variable will now be the decimal equivalent of the input binary number.

C code:
//C program to convert binary to decimal number
#include <stdio.h>

int main() {

    long long binaryNum;
    int decimal = 0, base = 1, remainder;

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

    //converting binary to decimal
    while (binaryNum != 0) {
        remainder = binaryNum % 10;
        decimal += remainder * base;
        base *= 2;
        binaryNum /= 10;
    }

    printf("Decimal equivalent: %d\n", decimal);

    return 0;
}
Output:
Enter a binary number: 11011
Decimal equivalent: 27

Time Complexity: The time complexity of the above code is O(log N), where N is the decimal equivalent of the binary number. 

Space Complexity: The space complexity of the above code is O(1), which means it uses a constant amount of additional space that does not depend on the input.

Related articles:

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)

DON'T MISS

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