CSC201 Lect4
CSC201 Lect4
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 either insert or extract characters to or from it.
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 cout.
cout is used in conjunction with the insertion operator (<<). Example:
cout << "You are Welcome"; // prints You are Welcome on screen
cout << 80; // prints number 80 on screen
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 constant strings 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.
In order to perform a line break on the output we must explicitly insert a new-line character
into cout. In C++ a new-line character can be specified as \n (backslash, n):
cout << "First sentence.\n ";
cout << "Second sentence.\n Third sentence.";
Additionally, 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 overloaded operator of extraction (>>) on the cin stream.
The operator must be followed by the variable that will store the data that is going 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
an input from cin (the keyboard) in order 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 the 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 and 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;
STRINGS
Many programs process text, not numbers. Text consists of characters: letters, numbers,
punctuation, spaces, and so on.
Strings are sequences 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 initialized even if you do not supply an initial value.
By default, a string variable is set to an empty string: a string containing no characters. An
empty string literal is written as "". Example:
string myAddress = "";
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 "Ahaoma", you can concatenate them to one
long string.
The result consists of all characters in the first string, followed by all characters in the
second string. For example,
string fname = "Ahaoma";
string lname = "Okeke";
string name = fname + lname;
results in the string "AhaomaOkeke"
What if you’d like the first and last name separated by a space? No problem:
string name = fname + " " + lname;
This statement concatenates three strings: fname, the string literal " ", and lname.
String Input
You can read a string from the console:
cout << "Please enter your name: ";
string name;
cin >> name;
When a string is read with the >> operator, only one word is placed into the string
variable.
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 by using the substr member function.
The member function call:
s.substr(start, length)
returns a string that is 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"
A curious aspect of the substr operation is the starting position. Starting position 0 means
“start at the beginning of the string”. The first position in a string is labelled 0,
the second one 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);
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 other's first name: ";
string second;
cin >> second;
string initials = first.substr(0, 1) + "&" + second.substr(0, 1);
cout << initials << endl;
return 0;
}
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 serve to specify what has to be done
by our program, when and under which circumstances.
Conditional structure
If statement - the if statement is used to implement a decision. The condition is the
expression that is being evaluated. If this condition is true, statement is executed. If it is
false, statement is ignored (not executed) and the program continues right after this
conditional structure.
Syntax: if (condition) statement.
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;
}
We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. It is used in conjunction with the if statement.
Syntax: if (condition) statement1 else statement2
For example:
#include <iostream>
using namespace std;
int main()
{
int x;
cout<<"the value of x";
cin>> x;
if (x > 0)
{
cout << "x is postive";
}
else{
cout << "x is negative";
}
return 0;
}
The if + else structures can be concatenated with the intention of verifying a range of
values. The following example shows its use:
#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;
}
Multiple Alternative
In many situations, we can have more than two cases. Decisions can be implemented with
multiple alternatives. For example:
#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 allows us to execute a block code among many alternatives.
The expression in the switch case is evaluated and compared with the values of each case
label. For example:
#include <iostream>
using namespace std;
int main()
{
int day;
cout<<"Enter todays 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;
}
Every branch of the switch must be terminated by a break instruction. 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.
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
Loop is a control structure that is 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 reduce the redundancy of the code.
C++ supports various types of loops like for loop, while loop, and do-while loop. Each
has its own 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 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 which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in
one line.
Syntax:
for (initialization expression; condition or test expression; update expression)
{
// body of the loop
// statements we want to execute
}
Initialization Expression - here we initialize 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 body of the loop and update the loop variable. Otherwise,
we exit the For loop. An example for test expression is i <= 5;
Update Expression - once the body of the loop has been executed, we increment or
decrement the value of the loop variable in the update expression.
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << " Learning c plus plus \n";
}
return 0;
}
Output:
Learning c plus plus
Learning c plus plus
Learning c plus plus
Learning c plus plus
Learning c plus plus
WHILE LOOP
While loops are used in situations where we do not know the exact number of iterations of
loop beforehand. The loop execution is terminated on the basis of test condition.
Syntax:
initialization expression;
while (test_expression)
{
// statements to execute in the loop body
update_expression;
}
Example
#include <iostream>
using namespace std;
int main()
{
int i = 0; // initialization expression
while (i < 5) // test expression
{
cout << "Learning C plus plus\n";
i++; // update expression
}
return 0;
}
DO WHILE LOOP
In do while loops also, the loop execution is terminated on the basis of test condition.
The main difference between do while loop and while loop is, in do while loop, the
condition is tested at the end of loop body, that is, do while loop is exit controlled whereas
the other two loops are entry controlled loops.
Note: In do while loop, the loop body will execute at least once irrespective of test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
}
while (test_expression);
Example
#include <iostream>
using namespace std;
int main()
{
int i = 2; // initialization expression
do
{
cout << " Learning C plus plus\n";
i++; // update expression
}
while (i < 5); // test expression
return 0;
}
Output:
Learning C plus plus
Learning C plus plus
Learning C plus plus
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 it 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";
}
}
JUMP STATEMENTS.
The break statement - using break we can leave a loop even if the condition for its end 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 count down 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.
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;
}