Blog

  • C++ Program to Make a Simple Calculator Using Switch Case Statement

    In this C++ program tutorial, we will write a code on how to make a simple calculator using switch statement in C++ or in other words create a simple calculator to add, subtract, multiply and divide using switch and break statement.

    In order to understand the program you need to know about the following topics in C++:


    C++ Program to Make a Simple Calculator Using Switch Case Statement

    # include <iostream>
    using namespace std;
    
    int main() 
    {
        char op;
        float num1, num2;
    
        cout << "Choose the operator to perform: +, -, *, / : ";
        cin >> op;
    
        cout << "\nEnter the First Number: ";
        cin >> num1;
        cout << "Enter the Second Number: ";
        cin >> num2;
    
        switch(op) 
        {
            case '+':
                cout << num1 << " + " << num2 << " = " << num1 + num2;
                break;
    
            case '-':
                cout << num1 << " - " << num2 << " = " << num1 - num2;
                break;
    
            case '*':
                cout << num1 << " * " << num2 << " = " << num1 * num2;
                break;
    
            case '/':
                cout << num1 << " / " << num2 << " = " << num1 / num2;
                break;
    
            default:
                // If chose other than the given options
                cout << "Error! Operation not supported";
                break;
        }
    
        return 0;
    }

    Output:

    Choose the operator to perform: +, -, *, / : +
    Enter the First Number: 20
    Enter the Second Number: 30
    20 + 30 = 50

    Choose the operator to perform: +, -, *, / : *
    Enter the First Number: 5
    Enter the Second Number: 12
    5 * 12 = 60

    Choose the operator to perform: +, -, *, / : &
    Enter the First Number: 12
    Enter the Second Number: 52
    Error! Operation not supported


  • C++ Program to Calculate Average Percentage Marks

    In this tutorial, you will learn to write a code on how to calculate the average percentage marks in C++. You may go through the following topics in C++:

    We will do calculate the total marks, average, and then the percentage of the subjects entered by the user. The program also takes the user input for the marks obtained in the subjects.

    How to find the average and Percentage of marks?

    Total Marks = Sum of the marks of all subjects
    Average Marks = Total Marks/No. of subjects
    Percentage = ((marks obtained)/(total marks) *100)


    C++ Program to find Total, Average and Percentage Marks

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int sub, i;
      float marks, total = 0.0 f, avg, perc;
    
      cout << "Enter the number of subjects: ";
      cin >> sub;
    
      cout << "Enter marks on each subject:\n";
      for (i = 0; i < sub; i++)
      {
        cin >> marks;
        total += marks;
      }
    
      // Average Calculation
      avg = total / sub;
    
      // Each marks is out of 100
      perc = (total / (sub *100)) *100;
    
      cout << "Total Marks Obtained: " << total;
      cout << "\nAverage Marks: " << avg;
      cout << "\nPercentage: " << perc;
    
      return 0;
    }

    Output:

    Enter the number of subjects: 5
    Enter marks on each subject:
    84
    67
    62
    80
    76
    Total Marks Obtained: 369
    Average Marks: 73.8
    Percentage: 73.8

    Here, the total marks are taken as 100 on each subject, you may take the total marks from the users too.


  • C++ Program to Calculate Product and Sum of all Elements in an Array

    In this tutorial, we will write a C++ program to find the sum and product of all elements of an array. You may go through the following topics in C++ used in the program below.

    Explanation: The program takes input for the size of an array and the elements of an array. Then the array is iterated using for loop and the sum and the product of an element are calculated. Lastly, the result is displayed.

    However, the program solves two separate questions at a time:

    • C++ program to calculate the sum of all elements in an array
    • C++ program to calculate the product of all elements in an array

    C++ Program to Calculate Product and Sum of all Elements in an Array

    Source code:

    #include<iostream>
    using namespace std;
    
    int main ()
    {
        int arr[10], size, i, sum = 0, product = 1;
        
        //user input
        cout << "Enter the size of an array: ";
        cin >> size;
        
        cout << "Enter " << size << " elements in an array: " << endl;
        for (i = 0; i < size; i++)
            cin >> arr[i];
        
        //calculation
        for (i = 0; i < size; i++)
        {
            sum += arr[i];
            product *= arr[i];
        }
        
        //Display
        cout << "\nSum of array elements: " << sum;
        cout << "\nProduct of array elements: " << product;
        return 0;
    }

    Output:

    Enter the size of an array: 5
    Enter 5 elements in an array:
    2
    3
    4
    5
    6
    Sum of array elements: 20
    Product of array elements: 720


  • C Program to Swap Two Numbers

    In this tutorial, we will learn how to swap two numbers in C program. Before that, if you may go through the following topics in C that are used in this program.


    C Program to Swap Two Numbers using temporary variable

    The program takes two number inputs from the user that needed to be swapped. And using a third variable, we swap the value. The third variable used is named temp in the program.

    #include<stdio.h>
    
    int main()
    {
        int a, b, temp;
        
        printf("Enter a: ");
        scanf("%d", &a);
        
        printf("Enter b: ");
        scanf("%d", &b);
        
        temp = a;
        a = b;
        b = temp;
        
        printf("The swapped values a: %d and b: %d", a, b);
        
        return 0;
    }

    Output:

    Enter a: 10
    Enter b: 20
    The swapped values a: 20 and b: 10

    You may want to check the following swapping program in C.


  • C Program to Swap Two Numbers without using Third Variable

    In this tutorial, we will write a C program to swap two numbers without using a temporary variable. There are two ways to swap variables.

    1. Using + and
    2. Using * and /

    Let us go through each of them with a C program. You may check out the following program.


    C Program to Swap Two Numbers without using Third Variable

    1. Using + and –

    #include<stdio.h>
    
    int main()
    {
        int a, b;
        printf("Enter a: ");
        scanf("%d", &a);
        
        printf("Enter b: ");
        scanf("%d", &b);
        
        
        a = a + b;  //a = 10 + 20 = 30
        b = a - b;  //b = 30 - 20 = 10
        a = a - b;  //a = 30 - 10 = 20
        
        printf("The swapped values a: %d and b: %d", a, b);
        
        return 0;
    }
    

    Output:

    Enter a: 10
    Enter b: 20
    The swapped values a: 20 and b: 10


    2. Using * and /

    #include<stdio.h>
    
    int main()
    {
        int a, b;
        printf("Enter a: ");
        scanf("%d", &a);
        
        printf("Enter b: ");
        scanf("%d", &b);
        
        a = a * b; //a = 10 * 20 = 200
        b = a / b; //b = 200 / 20 = 10
        a = a / b; //a = 200 / 10 = 20
        
        printf("The swapped values a: %d and b: %d", a, b);
        
        return 0;
    }
    

    Output:

    Enter a: 10
    Enter b: 20
    The swapped values a: 20 and b: 10

    Note that the swapping using / and * will not work if one of the swapping values is zero (0).


  • C Program to Convert Fahrenheit to Celsius

    In this tutorial, we will write a C Program to convert Fahrenheit into Celsius. Let us start by understanding the formula for the conversion of Fahrenheit into Celsius.

    Fahrenheit and Celsius, both are the unit for measuring the temperature. Fahrenheit is represented by oF and Celsius by oC.

    Formula to convert Fahrenheit into Celsius

    celsius = (fahrenheit – 32)*5/9


    C ProgrC Program to Convert Temperature from Fahrenheit to Celsius

    #include<stdio.h>
     
    void main()
    {
        float c,f;
     
        //user input
        printf("Enter the Fahrenheit value: ");
        scanf("%f",&f);
     
        //conversion
        c = (f - 32) * 5 / 9;
        
        //Display the result
        printf("Celsius: %.3f", c); 
    }

    Output:

    Enter the Fahrenheit value: 64
    Celsius: 17.778


  • Infix to Postfix Conversion in C Program using Stack

    Stack is very useful for storing data in the manner of the stack. It s useful when comes to the conversion of arithmetic expressions in high-level programming languages into machine-readable form. There are some complicated arithmetic expressions such as (A+B)*C(D/(E+D)). This form can be converted into polish notation using stack.

    Infix and Postfix Expression

    Infix expression contains the operator at the middle of the operands such as A+B. Whereas Postfix expression the operator goes to the end of the expression such as AB+.

    Let us go through an example in the C program.


    Infix to Postfix Conversion in C Program using Stack

    #include<stdio.h>
    #include<ctype.h>
    
    char stack[100];
    int top = -1;
    
    void push(char x)
    {
        stack[++top] = x;
    }
    
    char pop()
    {
        if(top == -1)
            return -1;
        else
            return stack[top--];
    }
    
    int priority(char x)
    {
        if(x == '(')
            return 0;
        if(x == '+' || x == '-')
            return 1;
        if(x == '*' || x == '/')
            return 2;
        return 0;
    }
    
    int main()
    {
        char exp[100];
        char *e, x;
        printf("Enter Infix expression : ");
        scanf("%s",exp);
        
        e = exp;
        
        while(*e != '\0')
        {
            if(isalnum(*e))
                printf("%c ",*e);
            else if(*e == '(')
                push(*e);
            else if(*e == ')')
            {
                while((x = pop()) != '(')
                    printf("%c ", x);
            }
            else
            {
                while(priority(stack[top]) >= priority(*e))
                    printf("%c ",pop());
                push(*e);
            }
            e++;
        }
        
        while(top != -1)
        {
            printf("%c ",pop());
        }return 0;
    }

    Output: Run 1

    infix to postfix output

    Output: Run 2

    infix to postfix output

  • Fizz Buzz Program in C

    In this tutorial, we will learn about Fizz Buzz Implementation in C programming. Let us start by understanding what Fizz Buzz is and its implementation in a program.

    Fizz Buzz Program

    A Fizz Buzz program prints the number from the range of 1 to n, where n is the input number taken from the user.

    • The program prints “FizzBuzz” if it is a multiple of 3 and 5.
    • The program prints “Fizz” if it is a multiple of only 3 but not 5.
    • The program prints “Buzz” is it is a multiple pf only 5 but not 3.
    • Lastly, it prints the number itself, if it is none of the above.

    Example:

    Input (n): 10
    Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz

    Now let us go through an example in the C program to implement FizzBuzz.


    Fizz Buzz Program in C

    //FizzBuzz program in C
    #include <stdio.h>
    
    int main()
    {
       int i, n;
    
       printf("Enter the number: ");
       scanf("%d", &n);
    
       for (i = 1; i <= n; i++)
       {
          // For FizzBuzz (3 *5 =15)
          if (i % 15 == 0)
             printf("FizzBuzz\t");
    
          // For Fizz (3)
          else if ((i % 3) == 0)
             printf("Fizz\t");
    
          // For Buzz (5)
          else if ((i % 5) == 0)
             printf("Buzz\t");
    
          else	//if none of the above print n
             printf("%d\t", i);
       }
    
       return 0;
    }

    Output:

    Enter the number: 20
    1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz


  • C Program to Find Length of a String Using strlen() Function

    In this section, we will write a C program to find the length of a string using strlen() function. But before, you may go through the following topic in C programming.

    The program will take the user input for the string. To find the length of a string, we use the built-in string function called strlen(). This function is present in the string.h header file.


    C Program to Find Length of a String Using strlen() Function

    // C program to find length of the string using strlen() function
    #include <stdio.h>
    
    int main()
    {
       char str[30];
       int length;
    
       printf("Enter a string: ");
       scanf("%s", str);
    
       length = strlen(str);
    
       printf("Length of %s is %d", str, length);
       return 0;
    }

    Output:

    Enter a string: simple2code
    Length of simple2code is 11

    You can also check the following:


  • C Program to Find the Length of a String without using Function strlen()

    In this section, we will write a C program to find the length of a string without using strlen() function. But before, you may go through the following topic in C programming.

    The program will take the user input for the string and iterate the string. It will count the number of characters present in the string.


    C Program to Find the Length of a String without using Function strlen()

    // C program to find length of the string without using strlen() function
    #include <stdio.h>
    
    int main()
    {
       char str[30];
       int i;
    
       printf("Enter a string: ");
       scanf("%s", str);
    
       for (i = 0; str[i] != '\0'; ++i);
    
       printf("The length of %s is %d", str, i);
       return 0;
    }

    Output:

    Enter a string: simple2code
    The length of simple2code is 11

    You can also check the following: