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 4
In Progress

C++: Else If Statement

Yasin Cakal 9 Nov 2021
Lesson Progress
0% Complete

But what if the program you are designing should be able to give a wider range than two possible outputs? For such conditions we add else if statements.

We continue to give conditions. It is written in a similar way as if repeating the if else statement again and again. if (condition) {code} else if (condition2) {code2} else {code3}Is the way to apply the else if statements.

However, in such codes, we add else if statements before the else clause and else if statements here have conditions. Let’s practice this with a program that displays the grade a student will receive based on their marks!

#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>=90)
    {
        std::cout<<"You got an A!";
    }
    else if(marks>=80)
    {
        std::cout<<"You got a B!";
    }
    else if (marks>=65)
    {
        std::cout<<"You got a C!";
    }
    else 
    {
        std::cout<<"You got an F!";
    }
}

Output:

How many marks did you get in the exam?
I got: 
You got a C!

We have used multiple else if statements in this code to understand how to use such statements.

Responses

Leave a Reply

%d bloggers like this: