Control flow
if-else
- C
- C++
src/c/basics/03-if-else.c
#include <stdio.h>
int main()
{
int age = 0;
printf("Please enter your age in years: ");
scanf("%d", &age);
if (age <= 18)
printf("You are not an adult.\n");
else if (age < 65)
printf("You are an adult.\n");
else
printf("You are a senior citizen.\n");
return 0;
}
src/cpp/basics/03-if-else.cpp
#include <iostream>
using namespace std;
int main()
{
int a = 6;
int b = 5;
if (a > b)
{
cout << "a is greater than b" << endl;
}
else if (a < b)
{
cout << "a is less than b" << endl;
}
else
{
cout << "a is equal to b" << endl;
}
return 0;
}
switch
- C
- C++
src/c/basics/03-switch.c
#include <stdio.h>
int main()
{
int age = 0, category;
printf("Please enter your age in years: ");
scanf("%d", &age);
if (age < 0)
category = 0;
else if (age <= 18)
category = 1;
else if (age < 65)
category = 2;
else
category = 3;
switch (category)
{
case 0:
printf("Invalid age.\n");
break;
case 1:
printf("You are not an adult.\n");
break;
case 2:
printf("You are an adult.\n");
break;
case 3:
printf("You are a senior citizen.\n");
break;
default:
printf("Should not be necessary here.\n");
break;
}
return 0;
}
src/cpp/basics/03-switch.cpp
#include <iostream>
using namespace std;
int main()
{
int age = 0, category;
cout << "Please enter your age in years: ";
cin >> age;
if (age < 0)
category = 0;
else if (age <= 18)
category = 1;
else if (age < 65)
category = 2;
else
category = 3;
switch (category)
{
case 0:
cout << "Invalid age." << endl;
break;
case 1:
cout << "You are not an adult." << endl;
break;
case 2:
cout << "You are an adult." << endl;
break;
case 3:
cout << "You are a senior citizen." << endl;
break;
default:
cout << "Should not be necessary here." << endl;
break;
}
return 0;
}
Ternary operator
- C
- C++
src/c/basics/03-ternary.c
#include <stdio.h>
int main()
{
int input1, input2, big;
printf("Enter two integer numbers (separated by space): ");
scanf("%d%d", &input1, &input2);
big = (input1 > input2) ? input1 : input2;
printf("Biggest number = %d\n", big);
return 0;
}
src/cpp/basics/03-ternary.cpp
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 9;
const char *s = x > y ? "Yes" : "No";
cout << s << endl;
return 0;
}