Back to Course

Introduction to C++

0% Complete
0/0 Steps
  1. C++: Basics
    5Topics
    |
    6 Quizzes
  2. C++: Compilation and Execution
    5Topics
    |
    6 Quizzes
  3. C++: Variables
    9Topics
    |
    10 Quizzes
  4. C++: Conditions Operators
    5Topics
    |
    6 Quizzes
  5. C++: Logical Operators
    3Topics
    |
    4 Quizzes
  6. C++: Loops and Errors
    8Topics
    |
    9 Quizzes
  7. C++: Vectors
    4Topics
    |
    3 Quizzes
Lesson 4, Topic 3
In Progress

C++: Else Clause

Yasin Cakal 9 Nov 2021
Lesson Progress
0% Complete

We executed a program where the result displayed if the student had passed an exam. What if you wanted a program that alternately printed the student had failed the exam? We add an else clause to the if statement for this. Now, if the if statement condition is not satisfied, the code will execute the code in else clause. If the if condition is satisfied, the code for the else clause is ignored.

For this, after the curly brackets of the if statement end, we type else and add the curly brackets for the else statement. Let’s try this in a code:

#include <iostream>

int main()
{
    int marks;
    std::cout<<"How many marks did you get in the exam?\n"<<"I got: \n";
    std::cin>>marks;
    if(marks>=60)
    {
        std::cout<<"You have passed the exam!";
    }
    else
    {
        std::cout<<"You have failed the exam!";
    }
}

Output:

How many marks did you get in the exam?
I got: 
22
You have failed the exam!

As we can see above:

  • If the if condition is satisfied, the code enter the curly brackets and executes the code within the curcly brackets. In this case, the code in the else statement curly brackets is completely skipped.
  • If the if condition is not satisfied, the code ignores the parentheses {} for the if statements and enter the else clause statement and executes the code within the curly brackets in the else clause.

Things to Remember: Only one of the codes from either if clause or else clause is executed.

Responses

Leave a Reply

%d bloggers like this: