If,If...Else & Nested If...Else

 


 

In computer programming, we use the if statement to run a block code only when a certain condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.

  • if the percentage is above 90, assign grade A
  • if the percentage is above 75, assign grade B
  • if the percentage is above 65, assign grade C

There are three forms of if...else statements in C++.

  1. if statement
  2. if...else statement
  3. if...else if...else statement

 

C++ if Statement

The syntax of the if statement is:

if (condition) {
   // body of if statement
}

The if statement evaluates the condition inside the parentheses ( ).

  • If the condition evaluates to true, the code inside the body of if is executed.
  • If the condition evaluates to false, the code inside the body of if is skipped

 

Example: C++ if Statement

// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter an integer: ";
    cin >> number;

    // checks if the number is positive
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    }
    cout << "This statement is always executed.";
    return 0;
}

Output 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

When the user enters 5, the condition number > 0 is evaluated to true and the statement inside the body of if is executed.

Output 2

Enter a number: -5
This statement is always executed.

When the user enters -5, the condition number > 0 is evaluated to false and the statement inside the body of if is not executed.

 

 

C++ if...else

The if statement can have an optional else clause. Its syntax is:

if (condition) {
    // block of code if condition is true
}
else {
    // block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.

If the condition evaluates true,

  • the code inside the body of if is executed
  • the code inside the body of else is skipped from execution

If the condition evaluates false,

  • the code inside the body of else is executed
  • the code inside the body of if is skipped from execution

 

C++ if...else...else if statement

The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.

The syntax of the if...else if...else statement is:

if (condition1) {
    // code block 1
}
else if (condition2){
    // code block 2
}
else {
    // code block 3
}

Here,

  • If condition1 evaluates to true, the code block 1 is executed.
  • If condition1 evaluates to false, then condition2 is evaluated.
  • If condition2 is true, the code block 2 is executed.
  • If condition2 is false, the code block 3 is executed.

 

Example: C++ if...else...else if

// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main() {
     int number;

    cout << "Enter an integer: ";
    cin >> number;
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    } 
else if (number < 0) {
      cout << "You entered a negative integer: " << number << endl;
     } 
else {
        cout << "You entered 0." << endl;
    }
     cout << "This line is always printed.";
    return 0;
}

Output 1

Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.

Output 2

Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.

Output 3

Enter an integer: 0
You entered 0.
This line is always printed.

In this program, we take a number from the user. We then use the if...else if...else ladder to check whether the number is positive, negative, or zero.

If the number is greater than 0, the code inside the if block is executed. If the number is less than 0, the code inside the else if block is executed. Otherwise, the code inside the else block is executed.

 

C++ Nested if...else

Sometimes, we need to use an if statement inside another if statement. This is known as nested if statement.

Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is another, inner if statement. Its syntax is:

// outer if statement
if (condition1) {
    // statements

    // inner if statement
    if (condition2) {
        // statements
    }
}

Notes:

  • We can add else and else if statements to the inner if statement as required.
  • The inner if statement can also be inserted inside the outer else or else if statements (if they exist).
  • We can nest multiple layers of if statements.

 


Example: C++ Nested if

// C++ program to find if an integer is even or odd or neither (0)
// using nested if statements

#include <iostream>
using namespace std;

int main() {
    int num;
    
    cout << "Enter an integer: ";  
     cin >> num;    

    // outer if condition
    if (num != 0) {
        
        // inner if condition
        if ((num % 2) == 0) {
            cout << "The number is even." << endl;
        }
         // inner else condition
        else {
            cout << "The number is odd." << endl;
        }  
    }
    // outer else condition
    else {
        cout << "The number is 0 and it is neither even nor odd." << endl;
    }
    cout << "This line is always printed." << endl;
}

Output 1

Enter an integer: 34
The number is even.
This line is always printed.

Output 2

Enter an integer: 35
The number is odd.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither even nor odd.
This line is always printed.

In the above example,

  • We take an integer as an input from the user and store it in the variable num.
  • We then use an if...else statement to check whether num is not equal to 0.
    • If true, then the inner if...else statement is executed.
    • If false, the code inside the outer else condition is executed, which prints "The number is 0 and neither even nor odd."
  • The inner if...else statement checks whether the input number is divisible by 2.
    • If true, then we print a statement saying that the number is even.
    • If false, we print that the number is odd.

 



 

 

Hello World

 

 

C++ "Hello World!" Program

// Your First C++ Program

#include <iostream>

int main() {
    std::cout << "Hello World!";
    return 0;
}


Output 

Hello World!

 

 

 

Working of C++ "Hello World!" Program

  1. // Your First C++ Program

    In C++, any line starting with // is a comment. Comments are intended for the person reading the code to better understand the functionality of the program. It is completely ignored by the C++ compiler.
  2. #include <iostream>

    The #include is a preprocessor directive used to include files in our program. The above code is including the contents of the iostream file.

    This allows us to use cout in our program to print output on the screen.

    For now, just remember that we need to use #include <iostream> to use cout that allows us to print output on the screen.
  3. int main() {...}

    A valid C++ program must have the main() function. The curly braces indicate the start and the end of the function.

    The execution of code beings from this function.
  4. std::cout << "Hello World!";

    std::cout prints the content inside the quotation marks. It must be followed by << followed by the format string. In our example, "Hello World!" is the format string.

    Note: ; is used to indicate the end of a statement.
  5. return 0;

    The return 0; statement is the "Exit status" of the program. In simple terms, the program ends with this statement.

ABOUT C++

 

 


 

 

C++ is a general-purpose object-oriented programming language developed by Bjarne stroustrup of Bell Labs in 1979. C++ was originally called ‘C with classes,’ and was built as an extension of the C language. Its name reflects its origins; C++ literally means ‘increment C by 1.’

It was renamed C++ in 1983, but retains a strong link to C, and will compile most C programs. Compared to C, C++ added object-oriented features to C such as classes, abstraction, and inheritance.

C++ is considered a mid-level programming language, combining some elements of low-level programming languages, such as the need to learn memory management, with high-level features.C++ is a high-level object-oriented programming language that helps programmers write fast, portable programs. C++ provides rich library support in the form of Standard Template Library (STL).

 

C++ Language Features

Some of the interesting features of C++ are:

  • Object-oriented: C++ is an object-oriented programming language. This means that the focus is on “objects” and manipulations around these objects. Information about how these manipulations work is abstracted out from the consumer of the object.
  • Rich library support: Through C++ Standard Template Library (STL) many functions are available that help in quickly writing code. For instance, there are standard libraries for various containers like sets, maps, hash tables, etc.
  • Speed: C++ is the preferred choice when latency is a critical metric. The compilation, as well as the execution time of a C++ program, is much faster than most other general purpose programming languages.
  • Compiled: A C++ code has to be first compiled into low-level code and then executed, unlike interpreted programming languages where no compilation is needed.
  • Pointer Support: C++ also supports pointers which are widely used in programming and are often not available in several programming languages.

It is one of the most important programming lanugage because almost all the programs/systems that you use have some or the other part of the codebase that is written in C/C++. Be it Windows, be it the photo editing software, be it your favorite game, be it your web browser, C++ plays an integral role in almost all applications that we use.

Uses/Applications of C++ Language

After exploring C++ features, let's have look at some interesting areas where C++ is popularly used.

Operating Systems

Be it Microsoft Windows or Mac OSX or Linux - all of them are programmed in C++. C/C++ is the backbone of all the well-known operating systems owing to the fact that it is a strongly typed and a fast programming language which makes it an ideal choice for developing an operating system. Moreover, C is quite close to the assembly language which further helps in writing low-level operating system modules.

Browsers

The rendering engines of various web browsers are programmed in C++ simply because if the speed that it offers. The rendering engines require faster execution to make sure that users don’t have to wait for the content to come up on the screen. As a result, such low-latency systems employ C++ as the programming language.

Libraries

Many high-level libraries use C++ as the core programming language. For instance, several Machine Learning libraries use C++ in the backend because of its speed. Tensorflow, one of the most widely used Machine Learning libraries uses C++ as the backend programming language. Such libraries required high-performance computations because they involve multiplications of huge matrices for the purpose of training Machine Learning models. As a result, performance becomes critical. C++ comes to the rescue in such libraries.

Graphics

All graphics applications require fast rendering and just like the case of web browsers, here also C++ helps in reducing the latency. Software that employ computer vision, digital image processing, high-end graphical processing - they all use C++ as the backend programming language. Even the popular games that are heavy on graphics use C++ as the primary programming language. The speed that C++ offers in such situations helps the developers in expanding the target audience because an optimized application can run even on low-end devices that do not have high computation power available.

Banking Applications

One of the most popularly used core-banking system - Infosys Finacle uses C++ as one of the backend programming languages. Banking applications process millions of transactions on a daily basis and require high concurrency and low latency support. C++ automatically becomes the preferred choice in such applications owing to its speed and multithreading support that is made available through various Standard Template Libraries that come as a part of the C++ programming kit.

Cloud/Distributed Systems

Large organizations that develop cloud storage systems and other distributed systems also use C++ because it connects very well with the hardware and is compatible with a lot of machines. Cloud storage systems use scalable file-systems that work close to the hardware. C++ becomes a preferred choice in such situations because it is close to the hardware and also the multithreading libraries in C++ provide high concurrency and load tolerance which is very much needed in such scenarios.

Databases

Postgres and MySQL two of the most widely used databases are written in C++ and C, the precursor to C++. These databases are used in almost all of the well-known applications that we all use in our day to day life - Quora, YouTube, etc.

Embedded Systems

Various embedded systems like medical machines, smartwatches, etc. use C++ as the primary programming language because of the fact that C++ is closer to the hardware level as compared to other high-level programming languages.

Telephone Switches

Because of the fact that it is one of the fastest programming languages, C++ is widely used in programming telephone switches, routers, and space probes.

Compilers

The compilers of various programming languages use C and C++ as the backend programming language. This is because of the fact that both C and C++ are relatively lower level languages and are closer to the hardware and therefore are the ideal choice for such compilation systems. These are a few uses and applications of C++ programming language. Now, let's know more about C++ advantages over other programming languages.

Advantages of C++ Language

C++ has the following 2 features that make it a preferred choice in most of the applications:

  • Speed: C++ is faster than most other programming languages and it provides excellent concurrency support. This makes it useful in those areas where performance is quite critical and the latency required is very low. Such requirements occur all the time in high-load servers such as web servers, application servers, database servers, etc. C++ plays a key role in such servers.
  • Closer to hardware: C++ is closer to hardware than most other programming languages like Python, etc. This makes it useful in those areas where the software is closely coupled with hardware and low-level support is required at the software level.

ABOUT


THANK YOU FOR VISITING NOT SOO GEEKY

 

I am ANKUR CHAHAR Founder,Administrator of this blog.

So basically i am from INDIA and am pursuing Engineering to be more specified B.Tech(CS with AI).

To find some exposure,improve productivity and enhance my knowledge and to enlighten the audience i started this blog  which in fact was in my mind for a long time but never the less better late than never

 

So lets just jump straight to the point the content would be on technical side and mainly consist of coding in C and C++ and some articles on Data Structures and Sorting as well.If it all goes well we would jump into python and AI as well.

 

As it is just the beginning of a new chapter let me know your valuable feedback  on what all content would you all be interested in so that the content quality keeps on increasing day by day .

 

THANK YOU FOR VISITING