Python: Count Number of True Elements in Numpy Array in Python

Method to find count number of true element in numpy array in python

In this article, we will study what are true elements in python and different methods to calculate the count of true elements in both 1-D and 2-D Numpy array. First, let see what are true elements in python.

True Elements

True elements in numpy array are equivalent to 1 and False element is equivalent to 0. So we can say that it is basically a boolean numpy array.

Now let us see different methods to count a number of True elements in a 1-D numpy array.

This is one of the methods to count a number of true elements in a numpy array. count_nonzero() method require 1 argument i.e. the name of numpy array and then it return the count of true element in numpy array. It also accepts axis as one of the arguments but we do not need it in this case.

Syntax: count_nonzero(arr, axis=None)

Let see this with the help of an example.

import numpy as np

arr1 = np.array([False, True, True, False,True])
arr2 = np.array([0,1,1,0,1])
count1 = np.count_nonzero(arr1)
count2 = np.count_nonzero(arr2)
print('Print count of True elements in array1: ', count1)
print('Print count of True elements in array2: ', count2)

Output

Print count of True elements in array1:  3
Print count of True elements in array2:  3

There are two things to notice in this example first is that in arr1 count of True is 3 hence we get output as 3 and the second thing to notice is that if we write 1 and 0 instead of True and False respectively then we will get the same output. Hence it is also verified that True is equivalent to 1 and False is equivalent to 0 in a numpy array.

  • Method 2-Using sum() function

sum() is another method to count a number of true elements in a numpy array. Here sum() method works in the same way that we see in basic python. It returns the sum of all the elements in a Numpy array. As True is equivalent to 1 and False is equivalent to 0 so the sum we get is equal to count of True elements.

syntax: sum(arr)

Let see this with the help of an example.

import numpy as np

arr1 = np.array([False, True, True, False,True])
count1 = sum(arr1)
print('Print count of True elements in array1: ', count1)

Output

Print count of True elements in array1:  3
  • Method 3 Using bincount() method

bincount() return list of occurrence of each value in numpy array. Let see this with an example.

import numpy as np

arr1 = np.array([False, True, True, False,True])
l = np.bincount(arr1)
print(l)

Output

[2 3]

Here we see that at index 0 it return the count of the number of false values and at index 1 it return a count of true values. So now using list indexing we can return the count of elements at the 1st index which is the count of True values in the Numpy array.

So these are the methods to count a number of True values in a 1-D Numpy array.

Now we see that how to calculate the count of numpy array in the 2-D array. The best part is that the above methods that we study are used to calculate the count of True elements in a 2-D numpy array but the difference is that we can give an extra parameter as the axis to calculate the count of True elements row-wise or column-wise.

  • Method 1-Using count_nonzero() method

The working of the method is the same that we study in the case of a 1-D numpy array. But here we have a choice that we can give the axis as a parameter or not. If we do not give axis as a parameter then this method will return the total count of True elements in a numpy array but if we give an axis it returns a list of the count of True element row-wise or column-wise. There are two axis

axis=1 means return count row-wise

axis=0 means return count column-wise

Let see this with the help of an example.

import numpy as np

arr_2d = np.array([ [False, True, True,False],
                    [True, False, True,False],
                    [False, True, True,False]])
count1 = np.count_nonzero(arr_2d)
count2 = np.count_nonzero(arr_2d,axis=1)
count3 = np.count_nonzero(arr_2d,axis=0)
print("Total count of True values",count1)
print("Count of True values row-wise",count2)
print("Count of True values column-wise",count3)

Output

 

Total count of True values 6
Count of True values row-wise [2 2 2]
Count of True values column-wise [1 2 3 0]
  • Method 2-Using sum() method

The working of the method is the same that we study in the case of a 1-D numpy array. But here we have a choice that we can give the axis as a parameter or not. If we do not give axis as a parameter then this method will return the total count of True elements in a numpy array but if we give an axis it returns a list of the count of True element row-wise or column-wise. There are two axis

axis=1 means return count row-wise

axis=0 means return count column-wise

Here we have to take care of one this that we can’t simply write sum() here we have to write np.sum() because we use axis as one of argument.

Let see this with the help of an example.

import numpy as np

arr_2d = np.array([ [False, True, True,False],
                    [True, False, True,False],
                    [False, True, True,False]])
count1 = np.sum(arr_2d)
count2 = np.sum(arr_2d,axis=1)
count3 = np.sum(arr_2d,axis=0)
print("Total count of True values",count1)
print("Count of True values row-wise",count2)
print("Count of True values column-wise",count3)

Output

Total count of True values 6
Count of True values row-wise [2 2 2]
Count of True values column-wise [1 2 3 0]

So these are the methods to count the number of True values in both 1-D and 2-D numpy array.

Python : Join / Merge Two or More Lists

Basic Concepts/Terminologies

In this article, we will discuss different ways to join two or more lists in python. Before going to the actual let us understand about lists in python.

List

The list is one of the data structures in python that is used to store multiple items in a single variable. The best thing about the list is that we can store the value of different data types in a single list i.e. we can store string, int, and float values in the same list.

l=[1,2,"list",3.3,"Raj",4]
print(type(l))

Output

<class 'list'>

In this example, we see how we can easily store different variables in the same list.

Ways to join two or more lists in python

  • Method 1-Using the “+” operator

Here the role of the “+” operator is the same as in maths. The “+” operator can easily join/merge two or more lists like we add two or more numbers in maths. In python, we called this concept concatenation. Let us see this concept with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
new_l=l1+l2
print(new_l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Here we see that how we easily concatenate our lists using the “+” operator. The second thing to notice here is that the list that comes before the “+” operator has also come before another list in the new list.

  • Method 2-Using for loop

This is also one of the methods to merge two or more lists in python. In this method, we iterate through all the elements in one list and append these elements in the second list. Fore appending element in the second list we can use the append() method which is an inbuilt method in a python list. Let us see this method with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
for item in l1:
    l2.append(item)
print(l2)

Output

[8, 1.1, 'list2', 1, 2, 'list1', 3.3, 'Raj', 4]
  • Method 3-Using list.extend()

extend() method is used to add all the elements of an iterable i.e. list, tuple, etc at the end of the list. The best thing about this method is that we don’t need to use it for loops. we simply pass our iterable as an argument in extend() function and our task will be done. This is an in-place method that means it made changes in an existing list instead of creating a new list.

syntax: list.extend(anotherList)

Let us see this method with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l1.extend(l2)
print(l1)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']
  • Method 4-Using list comprehensions

Before understanding this method let us take a quick look at what list comprehension is.

List comprehensions

List comprehension is a way of creating a new list from the existing list. It helps in solving the problem related to list in one line.

Let us see how to join two lists using list comprehension with the help of an example.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l = [y for x in [l1, l2] for y in x]
print(l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Here we how we easily join our two lists using list comprehension.

  • Method 5- Using itertools.chain()

Before understanding this method let us see what an itertools is.

itertools

It is a module in python that provides methods to work flexibly with different iterables in python. To use this module we have to import this using the import keyword in our program.

itertools.chain()

This method takes multiple iterables at a one-time group them and produces a single iterable as output.

syntax-itertools.chain(*iterables)

Here * indicates that we can pass multiple iterable as a parameter in this function.

Let us see this concept with the help of an example.

import itertools
l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l=itertools.chain(l1, l2)
merge_list=list(l)
print(l)
print(merge_list)

Output

<itertools.chain object at 0x000002A9837445F8>
[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

Explanation

This method returns a chain object as we see in the output. We convert this chain object to a list to get our desired output.

  • Method 6- Using unpacking or “*” operator

As the name suggests unpacking or “*:” is used to unpack the content of any iterables object. Hence we can unpack the content of two or more lists and then merge them to form a new list.

Note: This method works only in python3.6+ versions.

l1=[1,2,"list1",3.3,"Raj",4]
l2=[8,1.1,"list2"]
l = [*l1, *l2]
print(l)

Output

[1, 2, 'list1', 3.3, 'Raj', 4, 8, 1.1, 'list2']

So these are the methods to append two or more lists in python.

C++ Program to Display Fibonacci Series using Loops, Recursion, Dynamic Programming

C++ Program to Display Fibonacci Series

In the previous article, we have discussed about C++ Program to Reverse a Number. Let us learn how to Display Fibonacci Series in C++ Program. Know different methods to print Fibonacci series in C++ explained step by step with sample programs. You can use the technique of your choice to display the Fibonacci series in no time. You can use this quick tutorial over here as a reference to resolve any doubts of yours.

Methods to display Fibonacci series in c++

In this article, we understand how to display the Fibonacci series in c++. Methods that we will discuss are given below.

Before understanding these methods let us understand first what is Fibonacci series is. The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

Here we can see the next number in the series is the sum of the previous two numbers. Now we see different methods to display the series.

Method 1-Using Loops

In this method, we are given a number up to which we have to print the series. As we understand that in this series the next number is the sum of previous two numbers therefore we have to store first two number in a variable by ourself because these numbers are fixed and by these numbers, we can display the series. Let write the code for this.

C++ Program to print Fibonacci Series using Loops

#include <iostream>
using namespace std;

int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    cout << "Fibonacci Series: ";

    for (int i = 0; i < n-2; i++) {
       
        if(i == 0) {
            cout << t1 << " ";
        }
        if(i == 1) {
            cout << t2 << " ";
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << " ";
    }
    return 0;
}

Output

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Method 2: Using Recursion

As we understand that in this series the next number is the sum of the previous two numbers, therefore, we have to build faith in our program that the sum of the last two-digit will give the next digit, and by having this faith we call the recursive function. Let write code for this.

C++ Program to print Fibonacci Series using Recursion

#include <iostream>
using namespace std;

int fibonacci(int n){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    return fibonacci(n-1)+fibonacci(n-2);
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

Method – 3 Using Dynamic Programming

When we analyze the recursive code of the Fibonacci series we will see that we call the recursive function for a number multiple times which is not a good practice. In this approach, we will see that instead of calling recursive function for a given number again and again we store the result for that number in an array so that if that number come again instead of calling recursive call for that number we will simply return the result of that number from the array. Let write the code for this.

#include <iostream>
using namespace std;

int fibonacci(int n,int f[]){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    if(f[n] != -1){
        return f[n];
    }
    
    f[n] = fibonacci(n-1,f)+fibonacci(n-2,f);
    return f[n];
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm,f[10];
    for(int i=0;i<=n;i++)
    {
        f[i]=-1;
    }
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i,f)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

So these are the methods to display the Fibonacci series in c++.

Related Programs:

C++ Program to Check Whether a Character is a Vowel or Not

C++ Program to Check Whether a Character is a Vowel or Not

Methods to check whether the character is a vowel or not in c++

In this article, we discuss how to check whether a given character is a vowel or not in c++. The methods that are discussed are given below.

Let’s discuss these methods one by one.

Method 1-Using if-else statement

In this method, we will use the if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='u';
    
    if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else 
    {
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character u is a vowel

Note: Here we are writing code for lower case letters. We can use the same logic for upper case letters also.

Method 2-Using if-else if-else statement

In this method, we use the if-else if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='u';
    
    if(ch=='a')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='e')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='i')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='o')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else if(ch=='u')
    {
        cout<<"Character "<<ch<<" is a vowel";
    }
    else 
    {
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character u is a vowel

Method 3-Using switch statement

In this method, we use the switch statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='h';
    
    switch(ch)
    {
        case 'a': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'e': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'i': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'o': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        case 'u': 
        cout<<"Character "<<ch<<" is a vowel";
        break;
        default:
        cout<<"Character "<<ch<<" is not a vowel";
    }
    return 0;
}

Output

Character h is not a vowel

So these are the methods to check whether a given character is a vowel or not.

C++ Program to Check Whether a Character is an Alphabet or Not

C++ Program to Check Whether a Character is an Alphabet or Not

In the previous article, we have discussed C++ Program to Convert String to a Number. In this article, we will see C++ Program to Check Whether a Character is an Alphabet or Not.

Method to check whether a character is an alphabet or not in c++

In this article, we discuss different methods of how can we check whether a given character is alphabet or not in c++. The methods that are discussed are given below.

Let understand these methods one by one.

Method 1-Using if-else statement with ASCII value concept

As we know that ASCII value of upper case alphabets is between 65 and 90 i.e. ASCII value of ‘A’ is 65 while that of ‘Z’ is 90, while the ASCII value of lower case alphabets is between 97 and 122 i.e. ASCII value of ‘a’ is 97 while that of ‘z’ is 122. So we use this concept to check whether a given character is an alphabet or not. If the ASCII value of a character is between 65 and 90 or it is between 97 and 122 then the given character is an alphabet else given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

Method 2- Using if-else statement with comparing character concept

In this method instead of comparing the ASCII value of character, we will directly compare characters i.e. if a character is between ‘a’ and ‘z’ or a character is between ‘A’ and ‘Z’ then a given character is an alphabet otherwise given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

Method 3-Using isalpha( ) method

isalpha( ) is a function in C++ that can be used to check if the passed character is an alphabet or not. It returns a non-zero value if the passed character is an alphabet else it returns 0. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
    char ch='j';
     if (isalpha(ch))
     {
        cout <<"Character "<<ch<<" is an alphabet";
     }
     else
     {
         cout <<"Character "<<ch<<" is not an alphabet";
     }
    return 0;
}

Output

Character j is an alphabet

So these are the methods to check whether a given character is an alphabet or not in c++.

Do you want to learn how to write a simple program in C++ language? If yes, then tap on the C++ Sample Programs link and get the source code for sample and easy programs.

C++ Program to Convert Decimal Number to Octal Number

C++ Program to Convert Decimal Number to Octal Number

In the previous article, we have discussed about C++ Program to Convert Octal Number to Decimal Number. Let us learn how to Convert Decimal Number to Octal Number in C++ Program.

Methods to convert decimal number to octal number in c++

In this article, we discuss different methods by which we can convert decimal numbers to octal numbers in c++. The methods that we will discuss today are given below.

First, discuss the basic intuition behind converting decimal to octal numbers in c++. Suppose a number is 16 and we have to find an octal form of 16 then we can do like this:-

16%8==0     octal=0              16/8=2

2%8==2      octal=20            2/8=0

and we stop as our number becomes 0. So we get octal of a number like this. Now we will discuss different methods of doing this task.

Method 1-Using arithmetic operator with array

As we see in the example above we do the task in the same manner. We store the remainder of the number when divided by 8 in the array and after that, we divide the number by 8. We perform the following steps till our number is greater than 0. After that, we will print the elements of the array in the reverse form which will be the answer. Let’s write the code for this.

#include <iostream>
using namespace std;

void decimalToOctal(int n)
{
    int octalNum[100],num=n;
    int i = 0;
    while (n > 0) {
        octalNum[i] = n % 8;
        n = n / 8;
        i++;
    }
    cout<<num<<" in octal form is ";
    for (int j = i - 1; j >= 0; j--)
    {
        cout << octalNum[j];
    }
}

int main()
{
    int n = 16;
    decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

Method 2-Using arithmetic operator without the array

We can also do the same task without using the array. Here the idea is the same but instead of an array, we use a variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int decimalToOctal(int n)
{
     long long octalNumber = 0;
    int rem, i = 1, step = 1;

    while (n!=0)
    {
        rem = n%8;
        n /= 8;
        octalNumber += rem*i;
        i *= 10;
    }
    return octalNumber;
}

int main()
{
    int n = 16;
    cout<<n<<" in octal form is "<<decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

So these are the methods to convert decimal number to octal number in c++.

C++ Program to Convert Single Character to String

C++ Program to Convert Single Character to String

In the previous article, we have discussed about C++ Program to Find of Size of Datatypes. Let us learn how to  Convert Single Character to String in C++ Program.

Methods to Convert Single Character to String in c++

In this article, we discuss different methods of how we can convert a single character to a string in c++. The methods that we discuss are given below.

Let’s understand each method one by one.

Method 1-Using “=” operator

In this method, we simply assign a character value to a string. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str=ch;
    cout<<str;
    return 0;
}

Output

d

Method 2-Using “+=” operator

As we know a string is a collection of characters. So if we take an empty string and add the character to it so we can convert that character into the string. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str="";
    str+=ch;
    cout<<str;
    return 0;
}

Output

d

Method 3-Using append( ) function

This method is just similar to the += operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str.append(1,ch);
    cout<<str;
    return 0;
}

Output

d

Method 4-Using assign( ) function

This method is just similar to the = operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str.assign(1,ch);
    cout<<str;
    return 0;
}

Output

d

So these are the methods to convert a single character to a string in c++.

C++ is a powerful general-purpose programming language. It is mostly used to develop browsers, operating systems, games and so on. Beginners who want to know more inversions of C++ language can learn the Basic C++ Programs for a better and quick understanding of the coding.

C++ Program to Convert String to a Number

C++ Program to Convert String to a Number

In the previous article, we have discussed about C++ Program to Convert Single Character to String. Let us learn how to Convert String to a Number in C++ Program.

Program to Convert String to a Number in c++

In this article, we discuss how we can convert a string to a number in c++. For example, suppose we a string “123” then we have to convert it to integer 123. The methods that are discussed are given below.

Let’s discuss these methods one by one.

Method 1-Using stoi( ) function

The stoi() function takes a string as an argument and returns its value. Let’s understand this with the help of an example.

#include <iostream>
using namespace std;

int main() {
    string str="123";
    
    cout<<stoi(str)<<endl;
    
    string str1="123abd";
    cout<<stoi(str1);
    return 0;
}

Output

123
123

Method 2-Using atoi( ) function

 The atoi() function takes a character array or string literal as an argument and returns its value. Let’s understand this with the help of an example.

#include <bits/stdc++.h>
using namespace std;

int main() {
     const char* str1 = "123";
    cout<<atoi(str1)<<endl;
    
    
    const char* str2= "123 geek";
    cout<<atoi(str2)<<endl;
    return 0;
}

Output

123
123

So these are the methods to convert a string to a number in c++.

The list of C++ Example Programs include swapping number, addition, multiplication of two numbers, factorial of a number and many more. Interested people can get the cpp code to get a clear idea on the programming language.

C++ Program to Find Largest Number Among Three Numbers

C++ Program to Find Largest Number Among Three Numbers

In the previous article, we have discussed about C++ Program to Calculate Sum of First N Natural Numbers. Let us learn how to find Largest Number Among Three Numbers in C++ Program.

Method to find the largest number among 3 numbers in c++

In this article, we see different methods by which we can largest of 3 numbers using c++. Let see all the methods one by one.

Method 1-Using if statements

In this method, we use three if statements for all three numbers. In the first, if statement we will compare the first number with the second and third numbers and if it is greater than both the number then we will say number 1 is the largest. In the second if statement we will compare the second number with the first and third numbers and if it is greater than both the number then we will say number 2 is the largest. In the third, if statement we will compare the third number with the second and first numbers and if it is greater than both the number then we will say number 3 is the largest. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n1=10,n2=12,n3=9;
     if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    if(n3 >= n1 && n3 >= n2)
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Here we see that 12 is the largest among the 3 numbers.

Method 2-Using if-else statement

There is a flaw in the first method because in the first method all the if statement runs. Suppose if we get that number 1 is the greatest is greatest in first if statement then in that case also all if statement runs. So to improve this we can use the if-else statement. In if-else statements, if one condition pass then we will not go to further statements. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Method 3-Using nested if-else statement

This method is a more efficient version than the first two methods. Let write a code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if (n1 >= n2) {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Largest number: 12

Method 4-Using Ternary operator

The ternary operator is a way of using an if-else statement in one line.So by using the ternary operator we can reduce our code line with the same logic that we discuss above. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     int max = (n1 > n2) ?
          (n1 > n3 ? n1 : n3) :
          (n2 > n3 ? n2 : n3);
    cout << "Largest number among "
         << n1 << ", " << n2 << " and "
         << n3 << " is " << max << "." ;

    return 0;
}

Output

The largest number among 10, 12, and 9 is 12.

So these are the methods to find the largest among 3 numbers in c++.

C++ Program to Convert Octal Number to Decimal Number

C++ Program to Convert Octal Number to Decimal Number

In the previous article, we have discussed about C++ Program to Convert Decimal Number to Binary Number. Let us learn how to Convert Octal Number to Decimal Number in C++ Program.

Methods to Convert Octal Numbers to Decimal Numbers in C++

In this article, we will discuss different methods of converting octal to decimal numbers in c++. The list of the methods that we will discuss is given below.

Let discuss the basic idea for converting octal to a decimal number which will help us later in writing the code. Let discuss the approach with the help of an example. Suppose the octal number is 67 then its decimal form is 55. We will write 67 as 6*(8^1)+7*(8^0) which is equivalent to 55. So here we see we extract the digit of decimal number and multiply the digit with the power of 8 in increasing order. This means the first digit is multiplied with 8 to the power 0 while the second digit is multiplied with 8 to the power 1 and so on. So this is the intuition. Let’s discuss different methods to do it.

Method 1-Using Loop with arithmetic operator

In this approach, we will take the help of a loop and modulo(%) and division(/) operator to extract the digit of the binary number. When we extract the digit we will simply multiply the digit with a power of 8 and stored the result in the variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;


int convertOctalToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, rem;
    while (n!=0)
    {
        rem = n%10;
        n /= 10;
        decimalNumber += rem*pow(8,i);
        i++;
    }
    return decimalNumber;
}

int main()
{
    long long n=67;
    cout << n << " in octal is " << convertOctalToDecimal(n) << " in decimal";
    return 0;
}

Output

67 in octal is 55 in decimal

Method 2-Using pre-defined function

In c++ there is a pre-defined function that is used to convert octal to decimal numbers. Here we are talking about stoi() function. Let us see what the stoi() function is.stoi() stands for the string to integer, it is a standard library function in C++ STL, it is used to convert a given string in various formats (like binary, octal, hex, or a simple number in string formatted) into an integer. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string n="67";
    cout << n << " in octal is " <<  stoi(n, 0, 8) << " in decimal";
    
    return 0;
}

Output

67 in octal is 55 in decimal

So these are the methods to convert octal numbers to decimal numbers in c++.