0% found this document useful (0 votes)
9 views

04 - CSC 201 - Control Structures

Uploaded by

Don J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

04 - CSC 201 - Control Structures

Uploaded by

Don J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Content:

- Input and Output Operations


- C++ Strings
- Control Structures
o Conditional Structures
§ IF-ELSE statement
§ IF-ELSEIF Statement
§ Switch Statement
o Loops/Iterative Structures
§ FOR Statement
§ WHILE Statement
§ DO-WHILE Statement

1
INPUT AND OUTPUT OPERATIONS
• C++ uses a convenient abstraction called streams to perform input and output operations in
sequential media such as the screen or the keyboard.
• A stream is an object where a program can insert or extract characters.
• The standard C++ library includes the header file iostream, where the standard input and output
stream objects are declared.

Output (cout)
• By default, the standard output of a program is the screen, and the C++ stream object defined
to access it is the cout function.
• Cout is used in conjunction with the output operator (<<). Example:
// prints You are Welcome on-screen
cout << "You are Welcome";
// prints number 80 on screen
cout << 80;

• The << operator inserts the data that follows it into the stream preceding it. In the examples
above, it inserted the constant string “You are Welcome” and the numerical constant 80 into the
standard output stream cout.
• Whenever we want to use string literals (sequence of characters), we must enclose them between
double quotes (“”) so that they can be clearly distinguished from variable names.
• For example, these two sentences have very different results: cout
<< "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable
• The insertion operator (<<) may be used more than once in a single statement: cout
<< "I am, " << "Learning " << "C++ program";

• The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a
combination of variables and constants or more than one variable:
cout << "I am " << age << " years old and my name is " << name;

• It is important to notice that cout does not add a line break after its output unless we explicitly
indicate it.
• We must explicitly insert a new-line character into cout to perform a line break on the output. In
C++, a new-line character can be specified as \n (backslash, n):
cout << "First sentence.\n ";
cout << "Second sentence.\n Third sentence.";

2
• To add a new line, you may also use the endl manipulator. For example,
cout << "First sentence." << endl;
cout << "Second sentence." << endl;

Input (cin)
• The standard input device is usually the keyboard. Handling the standard input in C++ is done
by applying the input operator of extraction (>>) on the cin stream.
• The operator must be followed by the variable that will store the data to be extracted from the
stream. For example:
int age;
cin >> age;

• The first statement declares a variable of type int called age, and the second one waits for
input from cin (the keyboard) to store it in this integer variable.
• cin can only process the input from the keyboard once the ENTER key has been pressed.
• You must always consider the type of variable that you are using as a container with cin
extractions. If you request an integer, you will get an integer. If you request a character, you will
get a character; if you request a string of characters, you will get a string of characters.

#include <iostream>

using namespace std;

int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i * 2 << ".\n";
return 0;
}
• You can also use cin to request more than one datum input from the user:
cin >> a >> b; is equivalent to:
cin >> a;
cin >> b;

3
STRINGS
Many programs process text, not numbers. Texts consist of characters: letters, numbers, punctuation,
spaces, and so on. Strings are a sequence of characters. For example, the string "Okeke" is a sequence
of five characters.

String Type
• You can define variables that hold strings. For example:
string name = "Okeke";

• The string type is a part of the C++ standard. To use it, simply include the header file,
<string>:
#include <string>

• We distinguish between string variables (such as the variable name defined above) and
string literals (character sequences enclosed in quotes, such as "Okeke").
• The string stored in a string variable can change. A string literal denotes a particular string, just
as a number literal (such as 2) denotes a particular number.
• String variables are guaranteed to be initialised even if you do not supply an initial value. By
default, a string variable is set to an empty string containing no characters. An empty string literal
is written as "". Example:
string my_address = "";
String Concatenation
• Use the + operator to concatenate strings; that is, to put them together to yield a longer
string.
• Given two strings, such as "Okeke" and "Okafor", you can concatenate them into one long
string using the + operator. The result consists of all characters in the first string, followed
by all in the second string. For example,
string fname = "Okafor";
string lname = "Okeke";
string name = lname + fname;
results in the string "OkekeOkafor"
• What if you’d like the first and last names separated by a space? No problem:
string name = fname + " " + lname;
• This statement concatenates three strings: fname, the string literal " ", and lname.

4
String Input
• You can read a string from the console:
cout << "Please enter your name: ";
string name;
cin >> name;

• Only one word is placed into the string variable when a string is read with the >>
operator.

String Functions
• The number of characters in a string is called the length of the string.
• For example, the length of "Okeke" is 5. You can compute the length of a string with the
length function.
• The length function is invoked with the dot notation.
• That is, you write the string whose length you want, then a period, then the name of the
function, followed by parentheses:
int n = name.length();

• Many C++ functions require you to use this dot notation. These functions are called
member functions.
• Once you have a string, you can extract substrings using the substr member function. The
member function call: s.substr(start, length) returns a string made from the
characters in the string s, starting at character start and containing length characters. Example:
string greeting = "Good, Morning!";
string sub = greeting.substr(0, 4); // sub is "Good"

• The position of a character is zero-based indexed. This means it starts at 0. Starting position 0
means “start at the beginning of the string”. The first position in a string is labelled 0,
the second position is 1, and so on. For example, here are the position numbers in the

greeting string:
• Let’s figure out how to extract the substring "Morning". Count characters starting at 0. You find
that M, the 7th character, has position number 6. The string you want is 7 characters long.
Therefore, the appropriate substring command is
string m = greeting.substr(6, 7);

5
• If you omit the length, you get all characters from the given position to the end of the
string. For example, greeting.substr(7)

#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter your first name: ";
string first;
cin >> first;

cout << "Enter your significant last name: ";


string second;
cin >> second;

string initials = first.substr(0, 1) + "&" + second.substr(0, 1);


cout << initials << endl;
return 0;
}

6
CONTROL STRUCTURES
• One of the essential features of computer programs is their ability to make decisions.
• A program is usually not limited to a linear sequence of instructions.
• During its process, it may split, repeat code or take decisions.
• For that purpose, C++ provides control structures that specify what must be done by our
program, when and under which circumstances.

Conditional Structures
IF Statement: The if statement is used to execute a block of code if a specified condition is true.
Syntax:
if (condition) {
statement(s);
}

Example:
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "enter value for x";
cin >> x;

if (x > 0)
{
cout << "x is positive";
}
return 0;
}

• The IF statement is used to implement a decision. The condition is the expression that is being
evaluated. If this condition is true, the statement is executed. If it is false, the statement is ignored
(not executed), and the program continues right after this conditional structure.
• Optionally, you can use the else statement to specify an alternative block of code to execute if
the condition is false. It is used in conjunction with the if statement.

7
Syntax:
if (condition)
{
statement1;
}
else
{
statement2;
}

Example:
#include <iostream>
using namespace std;
int main()
{
int x;
cout <<"the value of x";
cin >> x;

if (x > 0)
{
cout << "x is positive";
}
else {
cout << "x is negative";
}
return 0;
}

Multiple Alternatives
• The if and else structures can be concatenated t o v e r i f y a range of values. The
following example shows its use:
• In many situations, we can have more than two cases. Decisions can be implemented with
multiple alternatives.

8
#include <iostream>
using namespace std;
int main()
{
int x;
cout<<"the value of x"; cin>> x;

if (x > 0)
{
cout << "x is positive";
}
else if (x < 0)
{
cout << "x is negative";
}
else
{
cout<<"x is zero";
}

return 0;
}

9
#include <iostream>
using namespace std;
int main()
{
int examscore;
cout << "enter exam score";
cin >> examscore;

if (examscore >= 70)


{
cout << "You scored A";
}
else if (examscore >= 60)
{
cout << "You scored B";
}
else if (examscore >= 50)
{
cout << "You scored C";
}
else if (examscore >= 45)
{
cout << "You scored D";
}
else
{
cout << "You failed";
}
return 0;
}

Switch Case
The switch statement is used to select one of many code blocks to execute based on the value of an
expression. It provides an alternative to using multiple if statements.
For example:

10
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter today’s day between 1-7";
cin >> day;

switch (day)
{
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}

• A break instruction must terminate every branch of the switch. If the break is missing, execution falls
through to the next branch, and so on, until finally, a break or the end of the switch is reached.
• In practice, this fall-through behaviour is rarely useful, but it is a common cause of errors. If you
accidentally forget the break statement, your program compiles but executes unwanted code.
• Many programmers consider the switch statement somewhat dangerous and prefer the if statement.

11
Nested If Statement
• It is often necessary to include an if statement inside another. Such an arrangement is called a
nested set of statements. This means we can place an if statement inside another if statement. For
example:
#include <iostream>
using namespace std;
int main()
{
int x = 20; if (x == 20)
{
//first if statement
if (x < 25)
{
cout << "x is smaller than 25" << endl;

if (x < 22)
{
cout << "x is smaller than 22 also" << endl;
}
}
else
{
cout << "x is greater than 25"<<endl;
}
}

return 0;
}

Loops/Iterative Structures
• A loop is a control structure used when we want to execute a block of code multiple times. It
usually continues to run until and unless some end condition is fulfilled.
• It is mainly used to reduce the length of the code by executing the same function multiple times
and reducing redundancy in the code.
• C++ supports loops like FOR loops, WHILE loops, and DO-WHILE l o o p s . Each has its
syntax, advantages, and usage.
• In a loop, we use a counter to check the condition for loop execution.
• In cases when the counter has not yet attained the required number, the control returns to the first
instruction in the sequence of instructions and continues to repeat the execution of the statements

12
in the block.
• If the counter has reached the required number, that means the condition has been fulfilled, and
control breaks out of the Loop of statements and comes outside of the loop to the remaining block
of code.

Types of Loops
• There are three types of Loops in C++ :
o For Loop
o While Loop
o Do While Loop

FOR Loop
• For loop is a repetition control structure that allows us to write a loop executed a specific number
of times. The loop enables us to perform n number of steps together in one line. It consists of three
parts: initialisation, condition, and update.
Syntax:
for (initialisation; condition; update)
{
// statement(s) to be executed repeatedly;
}

• Initialisation Expression – here, we initialise the loop variable to a particular value. For
example, int I = 1;

• Condition or Test Expression - here, we write the test condition. If the condition is met and returns
true, we execute the loop body and update the loop variable. Otherwise, we exit the For loop.
An example of a test expression is i <= 5;
• Update Expression - once the loop’s body has been executed, we increment or decrement the
value of the loop variable in the update expression.

13
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << i << ". Learning C++ \n";
}

return 0;
}

Output:
1. Learning C++
2. Learning C++
3. Learning C++
4. Learning C++
5. Learning C++

WHILE Loop
• While loops are used when we do not know the exact number of iterations of the loop
beforehand, the loop execution is terminated based on the test condition.
Syntax:
initialisation expression;
while (test_expression)
{
// statements to execute in the loop body;
update_expression;
}

14
Example
#include <iostream>
using namespace std;
int main()
{
int i = 0; // initialization expression
while (i < 5) // test expression
{
cout << "Learning C++ \n";
i++; // update expression
}
return 0;
}

DO-WHILE Loop
• In do-while loops, the loop execution is terminated based on the test condition.
• The main difference between the do-while loop and the while loop is in the do-while loop; the
condition is tested at the end of the loop body. The do-while loop is exit-controlled, whereas the
other two loops are entry-controlled loops.
Note: The loop body will execute at least once in a do-while loop, irrespective of the test
condition.
Syntax:
initialisation expression;
do
{
Statement(s)
update_expression;
}
while (test_expression);

15
Example

#include <iostream>
using namespace std;

int main()
{
int i = 2; // initialization expression

do
{
cout << i << ". Learning C++ ";
i++; // update expression
} while (i < 5); // test expression return 0;
}

Output:
2. Learning C++
3. Learning C++
4. Learning C++

Infinite Loop
• An infinite loop or an endless loop is a loop that does not have a proper exit condition for the
loop, making it run infinitely.
• This happens when the test condition is not written properly and permanently evaluates to true.
This is usually an error in the program.

Example:

#include <iostream>
using namespace std;
int main ()
{
int i;
for ( ; ; )
{
cout << "This loop runs indefinitely.\n";
}
}

16
Jump Statements
There are two types of jump statements used in loops in C++: The break and continue statements.
• The break statement - using break, we can leave a loop even if the end condition is not fulfilled.
It can be used to end an infinite loop or to force it to end before its natural end.
• For example, we are going to stop the countdown before its natural end (maybe because of an
engine check failure?):
#include <iostream>
using namespace std;
int main ()
{
int x;

for (x=10; x>0; x--)


{
cout << x << ", ";

if (x==3)
{
cout << "countdown aborted!"<< endl;
break;
}
}
return 0;
}

• The continue statement - causes the program to skip the rest of the loop in the current iteration
as if the end of the statement block had been reached, causing it to jump to the start of the
following iteration.

17
• For example, we are going to skip the number 5 in our countdown:
#include <iostream>
using namespace std;
int main ()
{
for (int x = 10; x > 0; x--) {
if (x == 5)
{
continue;
}
cout << x << ", ";
}

cout << "CONTINUE! \n";


return 0;
}

18

You might also like