LAB#3
LAB#3
LAB#3
Note:
In preparation of these materials have been taken from different online
sources in the shape of books, websites, research papers and presentations etc.
However, the author does not have any intention to take any benefit of these in her/his
own name. This lecture (audio, video, slides etc.) is prepared and delivered only for
educational purposes and is not intended to infringe upon the copyrighted material.
Sources have been acknowledged where applicable. The views expressed are
presenter’s alone and do not necessarily represent actual author(s) or the institution.
Instructor
Basic Input: C++ uses a convenient abstraction called streams to perform input and output
operations in sequential media such as the screen, the keyboard or a file. A stream is an entity
where a program can either insert or extract characters to/from. There is no need to know details
Manual
about the media associated to the stream or any of its internal specifications. All we need to
know is that streams are a source/destination of characters, and that these characters are
provided/accepted sequentially (i.e., one after another).
The standard library defines a handful of stream objects that can be used to access what are
considered the standard sources and destinations of characters by the environment where the
program runs:
strea
description
m
cin standard input stream
cout standard output stream
cerr standard error (output) stream
clog standard logging (output) stream
We are going to see in more detail only cout and cin (the standard output and input
streams); cerr and clog are also output streams, so they essentially work like cout, with the only
difference being that they identify streams for specific purposes: error messages and logging;
which, in many cases, in most environment setups, they actually do the exact same thing: they
print on screen, although they can also be individually redirected.
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
Example:
#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;
}
Output:
Please enter an integer value: 702
The value you entered is 702 and its double is 1404.
Example:
// cin with strings
#include <iostream>
Instructor
Manual
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}
Output:
What's your name? Homer Simpson
Hello Homer Simpson.
What is your favorite team? The Isotopes
I like The Isotopes too!
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
Extra Info:
stringstream
The standard header <sstream> defines a type called stringstream that allows a string to be
treated as a stream, and thus allowing extraction or insertion operations from/to strings in the
same way as they are performed on cin and cout. This feature is most useful to convert strings to
numerical values and vice versa. For example, in order to extract an integer from a string we can
write:
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
Instructor
Example:
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
Manual
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
Output:
Enter price: 22.25
Enter quantity: 7
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
Instructor
in a block, enclosed in curly braces: {}:
{ statement1; statement2; statement3; }
The entire block is considered a single statement (composed itself of multiple sub statements).
Manual
Whenever a generic statement is part of the syntax of a flow control statement, this can either be
a simple statement or a compound statement.
Selection statements: if and else
The if keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its
syntax is:
if (condition) statement
Here, condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is not executed (it is simply ignored), and the program continues
right after the entire selection statement.
For example, the following code fragment prints the message (x is 100), only if the value stored
in the x variable is indeed 100:
if (x == 100)
cout << "x is 100";
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
As usual, indentation and line breaks in the code have no effect, so the above code is equivalent
to:
if (x == 100) { cout << "x is "; cout << x; }
Selection statements with if can also specify what happens when the condition is not fulfilled, by
using the else keyword to introduce an alternative statement. Its syntax is:
if (condition) statement1 else statement2
where statement1 is executed in case condition is true, and in case it is not, statement2 is
executed.
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Several if + else structures can be concatenated with the intention of checking a range of values.
Manual
For example:
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
This prints whether x is positive, negative, or zero by concatenating two if-else structures. Again,
it would have also been possible to execute more than a single statement per case by grouping
them into blocks enclosed in braces: {}.
Instructor
int main()
{
cout<<"use of nested if"<<endl;
int a=10,b=20,c=30;
if(a>b)
{
Manual
if(a>c)
cout<<a<<"is largest "<<endl;
else if (c>b)
cout<<c<<"is largest"<<endl;
}
else
{
if (b>c)
cout<<b<<"is largest"<<endl;
else
cout<<c<<" is largest"<<endl;
}
return 0;
}
{
case constant1:
group-of-statements-1;
break;
case constant2:
group-of-statements-2;
break;
.
.
.
default:
} Instructor
default-group-of-statements
Manual
It works in the following way: switch evaluates expression and checks if it is equivalent to
constant1; if it is, it executes group-of-statements-1 until it finds the break statement. When it
finds this break statement, the program jumps to the end of the entire switch statement (the
closing brace).
If expression was not equal to constant1, it is then checked against constant2. If it is equal to this,
it executes group-of-statements-2 until a break is found, when it jumps to the end of the switch.
Finally, if the value of expression did not match any of the previously specified constants (there
may be any number of these), the program executes the statements included after the default:
label, if it exists (since it is optional).
Both of the following code fragments have the same behavior, demonstrating the if-else
equivalent of a switch statement:
switch example if-else equivalent
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
break;
else {
default:
cout << "value of x unknown";
cout << "value of x unknown";
}
}
The switch statement has a somewhat peculiar syntax inherited from the early times of the first C
compilers, because it uses labels instead of blocks. In the most typical use (shown above), this
means that break statements are needed after each group of statements for a particular label. If
break is not included, all statements following the case (including those under any other labels)
are also executed, until the end of the switch block or a jump statement (such as break) is
reached.
If the example above lacked the break statement after the first group for case one, the program
would not jump automatically to the end of the switch block after printing x is 1, and would
instead continue executing the statements in case two (thus printing also x is 2). It would then
Instructor
continue doing so until a break statement is encountered, or the end of the switch block. This
makes unnecessary to enclose the statements for each case in braces {}, and can also be useful to
execute the same group of statements for different possible values. For example:
switch (x) {
Manual
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}
Notice that switch is limited to compare its evaluated expression against labels that are constant
expressions. It is not possible to use variables as labels or ranges, because they are not valid C++
constant expressions.
To check for ranges or values that are not constant, it is better to use concatenations of if and else
if statements.
Sample Program # 3
#include<iostream>
using namespace std;
int main()
{
int a;
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
LAB TASKS
TASK # 01
Instructor
Run all the sample programs, note the output and get familiar with the syntax
TASK # 02
Manual
Write a program which take a number from the user and display weather the number is even or
odd
Sample Output:
Enter a number? 5
you have entered an odd integer
TASK # 03
Write a C++ code which take three inputs from user, your program should display the smallest
value (use nested if )
Sample Output:
Enter 1st value = 10
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
TASK # 04
Write a program which take 4 unique inputs from the user and find the largest number from
them.
(use logical operators for multiple conditions)
Sample Output:
Enter 1st value? 5
Instructor
Enter 2nd value? 9
Enter 3rd value? 10
Enter 4th value? 3
Largest number = 10
Manual
TASK # 05
Create a calculator in C++ which can perform addition, subtraction, multiplication, division
Ask the user to enter the operator first
then ask the user to enter first and then second value
Sample Output:
Please enter the operator which you want to perform? +
please enter first value? 5
Please enter second value? 6
5+6 =11
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
TASK # 06
Write a program to check whether a triangle is valid or not. The three angles of the triangle are
entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180
degrees.
Use Syntax # 02 of if-else statement for this task
TASK # 07
Given three points (x1, y1), (x2, y2) and (x3, y3), (x4,y4) write a program to check if all the
three points fall on one straight line.
Use Syntax # 02 of if-else statement for this task
Task # 08
Instructor
A library charges a fine for every book returned late. For first 7 days the fine is 10 PKR, for 8-14
days fine is 20PKR and above 14 days fine is 50PKR. If you return the book after 31 days your
Manual
membership will be cancelled. Write a program to accept the number of days the member is late
to return the book and display the fine or the appropriate message.
Task # 09
In a company, worker efficiency is determined on the basis of the time required for a worker to
complete a particular job. If the time taken by the worker is between 1– 2 hours, then the worker
is said to be highly efficient. If the time required by the worker is between 2 – 3 hours, then the
worker is ordered to improve speed. If the time taken is between 3 – 4 hours, the worker is given
training to improve his speed, if the time taken by the worker is between 4 - 5 hours, then a final
warning letter should be issued and, if the time taken by a worker is more than 5 hours, then the
worker has to leave the company. If the time taken by the worker is input through the keyboard,
find the efficiency of the worker.
TASK # 10
Create a Calculator using switch statement now
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Programming Fundamentals
Instructor
Manual