If statement code snippet
Summary
Source code
C++: if_statement.cpp
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
// if statement is used to make choice
// in the code. For example:
if (age < 21)
cout << "You are under 21. Sorry, you can't enter." << endl;
else
cout << "You are 21+. Welcome to the club." << endl;
cout << endl;
// also more compact version is available
// which is very handy for assignment or
// output statements:
// (condition) ? then : else
cout << "Age: " << ((age < 21) ? "Under 21" : "21+") << endl;
cout << endl;
// more complex conditions
if (age < 16)
cout << "You can't drive." << endl;
else if (age >= 16 && age < 18)
cout << "Restricted driver license is available to you." << endl;
else
cout << "You can apply for full driver license." << endl;
return 0;
}
C: if_statement.c
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
/* if statement is used to make choice
in the code. For example: */
if (age < 21)
printf("You are under 21. Sorry, you can't enter.\n");
else
printf("You are 21+. Welcome to the club.\n");
printf("\n");
/* also more compact version is available
which is very handy for assignment or
output statements:
(condition) ? then : else */
printf("Age: %s\n", (age < 21) ? "Under 21" : "21+");
printf("\n");
/* more complex conditions */
if (age < 16)
printf("You can't drive.\n");
else if (age >= 16 && age < 18)
printf("Restricted driver license is available to you.\n");
else
printf("You can apply for full driver license.\n");
return 0;
}
Sample run
C/C++
Enter your age: 23
You are 21+. Welcome to the club.
Age: 21+
You can apply for full driver license.