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

C++: If Statement

Yasin Cakal 9 Nov 2021
Lesson Progress
0% Complete

So far, we have tried programs that gave the same results every time you run them. But a little change and variety never hurt someone! It is the 21st century after all. Let’s start with if statements.

if statements test if an expression fulfills the condition and accordingly executes the programs. To use if statement, we write if (condition) {code to execute if the condition is fulfilled}. The code within the brackets is only run if the condition for the if statement is met. Otherwise, the entire code within the if statement is ignored and the program skips to the next part.

Let’s understand this by writing a code that tells a student if they have passed an exam.If not, it gives no output/

#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!";
    }
}

Output:

How many marks did you get in the exam?
I got: 

76
You have passed the exam!
  • The code works when the user enters a number greater than or equal to 60. In this code, a pair of parentheses () is written after the if keyword which determines if the statement is true or false.
  • Since in our case, the statement was true, the code within the curcly brackets was executed and the code printed You have passed the exam!.
  • If the statement is not fulfilled, the entire code within the curly brackets will be ignored and the code will execute nothing.

In this case, if the user inputs a value less than 60, the code would not have printed anything on the terminal.

Responses

Leave a Reply

%d bloggers like this: