C++ Program to Find Biggest of Three Numbers.

Here we will understand how to find the largest number among the three numbers using C++ code. 

Examples:
Input: int a = 5, b = 8, c = 2
Output: The Biggest number among the three is 8

Input: int a = 54, b = 21, c = 9
Output: The Biggest number among the three is 54

There are multiple ways to solve this problem:
  1. Using if statement.
  2. Using if-else statement.
  3. Using Ternary Operator.
1. Algorithm using if statement.
  • Take three input variables from the user and store them in three different variables a, b, and c.
  • Check condition if a >= b and a >= c, if both conditions are true then print "The Biggest number among three is a. 
  • Check condition if b >= a and b >= c, if both conditions are true then print "The Biggest number among three is b. 
  • Check condition if c >= a and c >= b, if both conditions are true then print "The Biggest number among three is c.  
  • Stop the Program.
//C++ Code to find Biggest among three numbers
#include<iostream>
using namespace std;

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

    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    if(a >= b && a >= c)
       cout<<"The Biggest number among the three is "<<a;

    if(b >= a && b >= c)
       cout<<"The Biggest number among the three is "<<b;

    if(c >= a && c >= b)
       cout<<"The Biggest number among the three is "<<c;
             
    return 0;                    
}
Output:
Enter three numbers: 10 34 54
The Biggest number among the three is 54

2. Algorithm using if-else statement
This algorithm is a little better than the previous one because here we are not going to check the remaining conditions once we find our first true condition.  
  • Take three input variables from the user and store them in three different variables a, b, and c.
  • Check first if-condition, a >= b and a >= c, if conditions are true then print "The Biggest number among three is a" and end the program.
  • Check the next else-if condition b >= a and b >= c, if conditions are true then print "The Biggest number among three is b" and end the program.
  • If both the above conditions fail then without checking any further conditions you can declare the third variable as the largest variable.
  • End the Program.
//C++ Code to find Biggest among three numbers
//using if-else 
#include<iostream>
using namespace std;

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

    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    if(a >= b && a >= c)
       cout<<"The Biggest number among the three is "<<a;
    else if(b >= a && b >= c)
       cout<<"The Biggest number among the three is "<<b;
    else
       cout<<"The Biggest number among the three is "<<c;
             
    return 0;                    
}
Output:
Enter three numbers: -5 4 5
The Biggest number among the three is 5

3. Algorithm using Ternary Operator.
The ternary operator is a shorter way of writing if-else conditions and based on the results of the condition a particular block of code executes.
  • (condition) ? expression 1 : expression 2
Here, if the condition is true then expression 1 will get executed and if the condition is false then expression 2 will get executed.
//C++ Code to find Biggest among three numbers 
//using ternary operator
#include<iostream>
using namespace std;

int main(){
    int a, b, c;
    int ans;
    cout << "Enter three numbers: ";
    cin >> a >> b >> c;

    //Ternary Operator
    ans = (a >= b ? (a >= c ? a : c) : (b >= c ? b : c));
    
    cout<<"The Biggest number among the three is "<<ans;
             
    return 0;                    
}
Output:
Enter three numbers: 5 3 12
The Biggest number among the three is 12

C++ Program to check a Prime Number.

To write code for Prime number checking first we need to understand what is Prime Number? Any number which is divisible only itself and 1 is known as Prime Number. Example: 2, 3, 5, 7, etc. You cannot divide these numbers with any other number except 1 and itself but one thing to make sure of here is that 0 and 1 are not Prime Numbers.


We can follow the below instructions to check if a number is Prime or not:

  • Create a boolean flag is_prime and mark and initially initialize it with true.
  • Check if the given number n is 0 or 1, if yes then set the is_prime flag value equal to false and print a message that the given number is not prime. 
  • If the n is greater than 1 then run a for loop from i = 2 up to i <= n/2 where n is the number that we need to check. Keep on incrementing the value of i by 1 with each iteration.

Note: We are running the loop up to n/2 because it is not possible to find any factor of n beyond n/2.(alert-passed)

  • In any iteration, the value of i perfectly divides the given value n then set the is_prime flag value equal to false and prints a message that the given number is not prime, else prints a message that the given number is a prime number.

Example: C++ Code to check Prime Number.

//C++ Code to check prime number
#include<iostream>
using namespace std;

int main(){

    int n;
    bool is_prime = true;

    cout<<"Enter a positive number: ";
    cin>>n;

    if(n == 0 || n == 1)
       is_prime = false;

    for(int i = 2; i <= n/2; i++){
        if(n % i == 0){
            is_prime = false;
            break;
        }
    }   

    if(is_prime)
       cout<<n<<" is a prime number.";
    else
       cout<<n<<" is not a prime number.";

    return 0;                    
}
Output:
Enter a positive number: 7
7 is a prime number.

How To Calculate Time Complexity of an Algorithm.

We calculate the Time and Space complexity of any algorithm by finding the growth rate of the function for different values of N where N is the size of our input. In most cases, we check an algorithm for a bigger value of N to get the worst-case time complexity of an Algorithm. 


It might be possible that one algorithm is giving the best results for smaller values of N and for the same problem another algorithm is giving the best results for larger values of N so we can't predict after which value of N one algorithm is better than other algorithm and this is the reason why we need to check for different values of N. 


But isn't it a tedious task to plug in different values of N to find the growth rate of any program? Here we use our Asymptotic Notations (more specifically Big O notation) to describe the growth rate or time complexity of our programs. 

Before going further into this topic to learn time complexity calculation, we will highly recommend you go through our Algorithms Introduction and Analysis post once. It will help you understand the terminologies used in this post. (alert-passed)  


What is Big O Notation?

When we want to find the running time of an algorithm we are not interested in calculating the exact running time because it is not possible to calculate the exact running time of each algorithm. We always calculate the approximate running time and Big O Notation helps us to achieve this. 


Big O Notation helps us find the time complexity in terms of the size of the input and the best part is that it gives us the upper bound of the function that tells us about the worse case time complexity of an algorithm because the function can never grow faster than this upper bound.


Condition for Big O Notation:

If f(n) and g(n) are the two functions, then

f(n) = O(g(n)) if there exists constants c and no such that f(n)  c.g(n), for all n  no.

Example: 
Given f(n) = n
Is f(n) = O(g(n))?

Let g(n) = 2n

f(n)  c.g(n)
   n  c.2n for all c = 1 and n. = 1

Yes, f(n) = O(g(n))
     f(n) = O(2n)  O(n) Linear Growth


Below is the growth rate of some Standard Functions.

Time complexity growth rate table


Let's understand the time complexity calculation with some example programs.

Example: Program to calculate the sum of first N natural numbers (using a loop).

//C++ Code to sum n natural numbers
#include<iostream>
using namespace std;

int main(){

    int sum = 0, n;              // ---> 1 time
    cin>>n;                      // ---> 1 time 

    for(int i = 1; i <= n; i++){ 
        sum = sum + i;           // ---> n times 
    }

    cout<<sum;                  // ---> 1 time 

    return 0;                   // ---> 1 time 
}
Output:
5
15

Calculation of Time complexity:

Total number of instruction = f(n) = n + 4

f(n) = n + 4
Let g(n) = n

f(n)  c.g(n)
n+4  c.n
n  4

Is f(n) = O(g(n)) ?
Yes, f(n)  c.g(n) for all n  no
where c = 2 and no = 4
f(n) = O(n) Linear Time Complexity

Example: Program to calculate the sum of first N natural numbers (using a formula).

//C++ Code to sum n natural numbers
#include<iostream>
using namespace std;

int main(){

    int sum = 0, n;              // ---> 1 time
    cin>>n;                      // ---> 1 time 

    sum = n*(n+1)/2;            // ---> 1 time
    cout<<sum;                  // ---> 1 time 

    return 0;                   // ---> 1 time 
}
Output:
5
15

Calculation of Time complexity:

Total number of instruction = f(n) = 5

f(n) = 5
Let g(n) = 1

f(n)  c.g(n)
5  c.1
Take c = 6
5  6

Is f(n) = O(g(n)) ?
Yes, f(n)  c.g(n) for all n  no
where c = 6 and no = 1
f(n) = O(1) Constant Time Complexity

In the above two examples, we have solved the same problem using two different methods to make you understand that multiple algorithms are present to solve one particular problem. Here the first approach is giving us time complexity O(n) and the second approach is giving us time complexity O(1) so we will use the second solution as constant time complexity is much faster than linear time complexity. 

What is the time complexity of the below function?
void fun(int n){
  int i, j;
  for(i = 1; i <= n/3; i++){    //Loop 1
     for(j = 1; j <= n; j+=4){  //Loop 2
         cout<<"Hello";
     }
  }
}
Answer:
Calculation of Time complexity:

For Loop 1:Loop is running from i = 1 to i = n/3 and incremented by one
unit each time.

Iteration 1: i = 1
Iteration 2: i = 2
Iteration 3: i = 3
          .
          .
          .
Iteration k: i = n/3 = k O(n)
Time Complexity = O(n)

For Loop 2: Loop is running from j = 1 to j = n and incremented by four
unit each time.

Iteration 1: j = 1
Iteration 2: j = 1 + 4
Iteration 3: j = 1 + 4 + 4 = 1 + 2*4
          .
          .
          .
Iteration k: j = n = 1 + (k - 1)*4
      n = 1 + (k - 1)*4
    n-1 = (k - 1)*4
(n-1)/4 = (k -1)
(n-1)/4 + 1 = k O(n)
Time Complexity = O(n)      

Total Time Complexity = O(n) x O(n) = O(n^2)

Time Complexities of Common Programming Conditions:

Loops: Normal loops usually execute for n number of times where n is the size of input present.
for(int i = 0; i < n; i++){
    //statements
}
  • The above loop executes n times.
  • Time Complexity: O(n)


Nested Loops: One loop run inside another loop and we can multiply the running time of both loops to get the total time.

for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++)
        //statements
}
  • The outer loop executes n times and the inner loop also executes n times.
  • Time Complexity: O(nxn) = O(n^2)

Consecutive statements: Series of statements and conditions are present inside a function and to get the total running time of the function we sum the time taken by each individual condition.
int n = 10;                // 1 time
int sum = 0;               //1 time

for(int i = 1; i <= n; i++){
   //statements           //n times
}

for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++)
        //statements       //n^2 times
}
  • The first two lines of code will take constant time to execute, the single for loop statement will execute n times and the nested for loops will execute n^2 times. 
  • Time Complexity: O(n^2 + n + 2) = O(n^2)

If-then-else statement: Usually taken constant time but if nested loops are present then we have to include their running time as well.
if(n == 0){               // ---> 1 time    
  //statement            // ---> 1 time
}
else{
   for(int i = 1; i <= n; i++){
       //statement       // ---> n times
   }
}
  • For if part it will take constant time (1 + 1 = O(1)) and for else part it will take constant time for condition checking and statement will execute n times (1 + n = O(n)).
  • Time Complexity: O(1) + O(n) = O(n)

Logarithmic Complexity: Logarithmic time complexity is achieved when the problem size is cut down by a fraction. log2(n) - Logarithmic equation tells us how many times 2 has been multiplied by itself in order to obtain value n.
//Example of Logarithmic growth
while(i <= n){
   //statement
   i = i*2;
}
Logarithmic Complexity

  • Time Complexity: O(log2n) 
I hope you found this post useful, please share your valuable feedback in the comment section below and share the post with other so we can keep on providing more such valuable content.(alert-success)

C++ Program to Add Two Numbers.

Adding two numbers in C++ programming is a very basic beginner-level question and one can easily write the code by following the below instructions. 

Instruction:

  • Declare two integer-type variables num1 and num2.
  • Take two integer-type input variables from the user which we are going to store in num1 and num2.
  • Declare another integer-type variable sum and initialize the variable with 0.
  • Add two variables num1 and num2 and store the answer in the sum variable.
  • Print the value present in the sum variable.

C++ Code to Add Two Integer Type Numbers.

#include<iostream>
using namespace std;

int main(){

    int num1, num2;
    
    cout<<"Enter the first number: ";
    cin>>num1;
    
    cout<<"\nEnter the second number: ";
    cin>>num2;

    int sum = 0;
    sum = num1 + num2;
    //Print sum 
    cout<<"Sum of two numbers: "<<sum;
    
    return 0;
}
Output:
Enter the first number: 10
Enter the second number: 5
Sum of two numbers: 15

Note: For this example, we are using an integer-type variable but you can change your change the data type of your variables based on the requirement like you can use float-type variables to add decimal values.(alert-success)

C++ Code to Add Two Float Type Numbers.

#include<iostream>
using namespace std;

int main(){

    float num1, num2;
    
    cout<<"Enter the first number: ";
    cin>>num1;
    
    cout<<"\nEnter the second number: ";
    cin>>num2;

    float sum = 0;
    sum = num1 + num2;
    //Print sum 
    cout<<"Sum of two numbers: "<<sum;
    
    return 0;
}

Output:

Enter the first number: 3.4
Enter the second number: 5.3
Sum of two numbers: 8.7

I hope you found this post useful, please write your comments below if you have any questions or feedback related to this topic.

Find Minimum Sum of Two Number Formed from Splitting Four Digit Number.

Given a four-digit positive integer say num, split the given integer to form two new numbers say num1 and num2. All the digits present in num should be used and leading zeros are allowed for the formation of new numbers. Return the minimum possible sum of new numbers num1 and num2.

Example 1:

Input: num = 2832
Output: 51

Explanation: 
Some possible pairs of numbers [num1, num2]:
[2, 832] = 2 + 832 = 834
[28, 32] = 28 + 32 = 60
[283, 2] = 283 + 2 = 285
[23, 28] = 23 + 28 = 51
etc.
The minimum possible sum of new numbers that can be obtained is [23, 28] = 23 + 28 = 51 Example 2: Input: num = 5008 Output: 13 Explanation: Some possible pairs of numbers [num1, num2]: [00, 58] = 0 + 58 = 58 [00, 85] = 0 + 85 = 85 [05, 08] = 5 + 8 = 13 [50, 08] = 50 + 8 = 58 etc. The minimum possible sum of new numbers that can be obtained is [05, 08] = 5 + 8 = 13

Approach 1: Using Sorting.
To solve this problem we do not need to generate all possible combinations of numbers and the length of num1 and num2 is going to be equal in all ideal cases. For creating the two smallest numbers that give you the minimum sum, the smaller digits should appear at the most significant position.

Below are the steps to solve this:
1. Convert the given 4-digit number into an array of digits.
2. Sort the array into increasing order.
3. Traverse the array from 0 to size and create two numbers:
  • num1 is going to be formed by digits present at odd positions in the array.
  • num2 is going to be formed by digits present at even positions in the array.
4. Return the sum of both digits (num1 + num2).

Below is the Code Implementation:

/*C++ Code for Find Minimum Sum of Two Number Formed 
from Splitting Four Digit Number.*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int minimumSum(int num){
    int num1 = 0, num2 = 0;
    int ans = 0;
    //using vector instead of array
    vector<int> vnum;
    //breaking 4 digit number and storing 
    //each digit into integer array
    while(num){
        int rem = num%10;
        vnum.push_back(rem);
        num = num/10;
    }
    //sorting the created list in ascending order
    sort(vnum.begin(), vnum.end());
    //forming num1 and num2
    for(int i = 0; i < vnum.size(); i++){
        if(i % 2 == 0)
           num1 = num1*10 + vnum[i];
        else
           num2 = num2*10 + vnum[i];   
    }
    return num1 + num2;
}

int main(){
    int num = 5008;
    //function call
    cout<<minimumSum(num);
}
Output:
13
  • Time Complexity: O(nlogn) because we also have to perform sorting.
  • Space Complexity: O(n) where n is the number of digits present.

Approach 2: Using String.
The logic of this approach is almost the same as the previous one but the only benefit is that you don't have to deal with the step of creating an array of digits.

Below are the steps to solve this problem:
1. Convert the given number into a string.
2. Sort the created string in ascending order.
3. Traverse the sorted string from 0 to size and create two numbers:
  • num1 is going to be formed by digits present at odd positions in the string.
  • num2 is going to be formed by digits present at even positions in the string.
4. Return the sum of both numbers (num1 + num2).

Below is the Code Implementation:

/*C++ Code for Find Minimum Sum of Two Number Formed 
from Splitting Four Digit Number.*/
#include<iostream>
#include<algorithm>
using namespace std;

int minimumSum(int num){
    int num1 = 0, num2 = 0;
    int ans = 0;
    //converting number to string
    string str = to_string(num);
    //sorting the convert string in ascending order
    sort(str.begin(), str.end());
    //forming num1 and num2
    for(int i = 0; i < str.size(); i++){
        if(i % 2 == 0)
           num1 = num1*10 + (str[i] - '0');
        else
           num2 = num2*10 + (str[i] - '0');   
    }
    return num1 + num2;
}

int main(){
    int num = 5008;
    //function call
    cout<<minimumSum(num);
}
Output:
13
  • Time Complexity: (nlogn)
  • Space Complexity: O(n)
I hope you found this post useful, please write your comments below if you want to give us any feedback to improve our content.

DON'T MISS

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