C++ Control Flow

C++ if/else:

#include <iostream>

using namespace std;

int main() {

int x = 1;

if (x + 1 == 2) {

cout << “if it evaluates to true, you see this” << endl;

} else {

cout << “you see this if the condition is false” << endl;

}

// second test with else if

double cost = 5.00;

double yourPayment = 4.90;

if (cost == yourPayment) {

cout << “You paid the right amount” << endl;

} else if (cost < yourPayment) {

cout << “You paid too much” << endl;

} else {

cout << “You didn’t pay enough” << endl;

}

return 0;

}

C++ for loop:

#include <iostream>

using namespace std;

int main() {

for (int i = 0; i <= 10; i++) {

cout << i << endl;

}

return 0;

}

C++ “for each” loop:

#include <iostream>

using namespace std;

int main() {

int foreachArray[3] = {333, 444, 555};

for (int item : foreachArray) {

cout << item << endl;

}

return 0;

}

C/C++ while loop:

#include <iostream>

using namespace std;

int main() {

int counter = 0;

while (counter <= 10) {

cout << counter << endl;

counter++;

}

return 0;

}

Switch/case:

#include <iostream>

using namespace std;

int main() {

cout << “pick a number from 1 to 5” << endl;

//this is a useless program

//that is only meant to demonstrate

//how switch/case is done in C++

int number = 2;

switch (number) {

case 1:

case 2:

case 3:

cout << “hello” << endl;

break;

case 4:

cout << “goodbye” << endl;

break;

case 5:

cout << “you win!” << endl;

break;

default:

cout << “invalid choice” << endl;

break;

}

return 0;

}

In the above example, there is a choice between 1 and 5, with actions determined with switch/case. In this particular example, choices 1, 2, and 3 do the exact same thing. 4 and 5 do different things, and any other value (the “default” section) will result in the message “invalid choice” being displayed.

← Previous | Next →

C++ Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *