C++ Manual
C++ Manual
C++ Manual
Lab # 01
Decision Making in C++
Objective:
Decision making using the if , if-else & switch-case structure.
Decision Making:
Statements are used when we wants to execute the statements as according to the user needs. A
user can Change the Sequence of the Statements for Execution. Many Times we wants to Execute
the Set of Instructions to be executed in one Situation and other Statements in other Situations
for Executing the Statements in Specific Situation there are Some Decision Making statements or
decision Control Statements those are provided by the C++ Language. In The decision First a
condition is checked it is true then it Executes the next Instruction otherwise it executes other
Statements.
General from of a typical decision making structure found in most of the programming
languages
The if statement
The if-else statement
The Switch statement
The if statement:
The if statement enables you to test for a condition ( such as whether two variables are equal )
and branch to different parts of your code, depending on the result or the conditions with
relational and logical operators are included.
Syntax : if (expression)
statement;
Example of if statement:
void main()
{
int num;
cout<<"Enter a number to check.\n";
cin>>num;
if(num<0) /* checking whether number is less than 0 or not & If test condition is true,
statement above will be executed, otherwise it will not be executed */
cout<<"Number : ”<<num;
cout<<"The if statement is true.";
}
Output:
Enter a number to check.
-2
Number=-2
The if statement is true.
Syntax:
if (test expression)
statements to be executed if test expression is true;
else
statements to be executed if test expression is false;
else
cout<<"Fail";
If the test is true then the next statement is executed, if is false then the statement following the
else is executed. After this, the rest of the program continues as normal.
If more than one statement following the “if” or the “else”, the statements written in the body of
the “if” and “else” Such a grouping is called a compound statement or a block.
}
if (exp 2)
{
statement 2;
----------
}
else
{
statement;
}
In the above example exp 1 will be evolved independently. Means, exp 2 will be executed what is
the result (true/ false) of exp 1. It is noted that “else” will be executed if all the test condition result
is false.
Syntax:
if (test expression)
statements to be executed if test expression is true;
else
if(test expression 1)
statements to be executed if test expressions 1 is true;
else
if (test expression 2)
.
.
else
statements to be executed if all test expressions are false;
If the test expression is true, it will execute the code before else part but, if it is false, the control
of the program jumps to the else part and check test expression 1 and the process continues. If all
the test expression are false then, the last statement is executed.
else
cout<< "Result:” << numb2 << numb1 ;
}
Output:
Enter two integers to check.
5
3
Result: 5>3
Or
Enter two integers to check.
4
4
Result: 4=4
Example 2 of Else-if
if (result >= 75)
cout<<"Passed: Grade A";
else if (result >= 60)
cout<<"Passed: Grade B";
else if (result >= 45)
cout<<"Passed: Grade C";
else cout<<" Failed";
In the above example evolving of exp 2 will depend on exp 1. Means, 2 will be evolved if exp
1evolved as false. But else will be executed if all the test conditions evolve as false.
Example 3:
int my_num = 3;
if ((my_num > 2) && (my_num < 4))
{
cout<<” my_num is three " ;
}
Or:
int my_num =3;
if (my_num > 2)
{
if (my_num < 4)
{
cout << "my_num is three" ;
}
}
Switch case:
ENGR. FARHAN AHMED Page 5
Computer Programming Principles
A switch statement allows a variable to be tested for equality against a list of values.
This statement is similar to if –else but it uses matching operations rather than checking a
condition if we wants to check many conditions then the program will very complex so in that
situation we will use switch statement switch statement uses many cases rather and it matches
the value with case where it matches it will execute the statement but there is very necessary to
stop the execution of each case so that it doesn’t execute next case so that for this purpose we
have to put the break statement after ending of an each case we know if uses else statement if
condition is false or all conditions are false the code of else statement is executed if code of all if
statements is false so that in switch default is used when all cases are not matched. The switch
statement provides a way of choosing between a set of alternatives, based on
The value of an expression. The general form of the switch statement is:
First expression (called the switch tag) is evaluated, and the outcome is compared to each of the
numeric constants (called case labels), in the order they appear, until a match is found. The
statements following the matching case are then executed. Note the plural: each case may be
followed by zero or more statements (not just one statement). Execution continues until either a
break statement is encountered or all intervening statements until the end of the switch statement
are executed. The final default case is optional and is exercised if none of the earlier cases
provide a match.
For example, suppose we have parsed a binary arithmetic operation into its three components
and stored these in variables operator, operand1, and operand2. The following switch statement
performs the operation and stored the result in result.
Example 01
main()
{
char grade;
cout<<"Enter your grade: ";
cin>>grade;
switch (grade)
{
case 'A':
cout<<”Your average must be b/w
90 – 100”;
break;
case 'B':
cout<<”Your average must be b/w
80 - 89";
break;
case 'C':
cout<<“Your average must be b/w
70 - 79");
break;
case 'D':
cout<<”Your average must be b/w
60 - 69");
ENGR. FARHAN AHMED Page 7
Computer Programming Principles
break;
default:
cout<<”Your average must be below 60”;
}
}
Example 02
main()
{
char operator ;
int a=10,b=5, result;
cin>> operator;
switch(operator)
{
case ‘+’ :
result = a+ b;
break;
case ‘-‘ :
result = a – b ;
break;
case ‘*’ :
result = a * b;
break;
case ’/’ :
result = a/ b ;
break;
default:
cout <<”Unknown Operator” ;
break;
}
}
Assignment:
1. Practice all the above programs & attach all programs with the lab assignment.
2. Write a program code to check whether a character is vowel or consonant using if –else
3. Write a program code to check whether a character is vowel or consonant using conditional
statement.
4. Write a program code which take input a number and check whether a number is even or odd
using if-else.
5. Write a program code which take input a number and check whether a number is even or odd
using conditional statement.
6. Write a program that take 3 integer inputs from user and find the largest number among three
a) main()
{
float a = 3.5;
switch(a)
{
case 0.5:
cout<< ” \n The Art Of C++ “;
break;
case 1.5:
cout<< “ \n The Spirit Of C++ “ ;
break;
case 2.5:
cout<< “\n See Through C++ “;
break;
case 3.5:
cout<< “\n The Simple C++ “;
}
}
b) main()
{
int temp ;
cout<< “ enter temp : “
cin>>temp;
switch(temp)
{
case(temp <=20):
cout<< “ \n Ooooooooooh! Damn Cool “;
case(temp > 20 && temp <= 30 ):
cout<< “ \n Rain Here “ ;
case(temp > 30 && temp <=40 ):
cout<< “ Wish I am on Everest“;
default:
3. Find out errors in the following Program. And rewrite the Program with output after
correcting.
a) main()
{
char suite ;
cin>>suite;
switch( a )
{
case 1:
cout << “ \n Dimond “ ;
case 2:
cout << “ \n Spade “ ;
default:
cout << “ \n Heart” ;
}
cout<< “ \n thought one wears a suite “ ;
}
b) main ()
{
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
ENGR. FARHAN AHMED Page 10
Computer Programming Principles
}
cout << "Your grade is " << grade << endl;
}
Lab # 02
Loops in C++
Objective:
Understanding the for, while, do-while and nested loops.
main()
{
for(inti = 0; i < 102; i = i + 5)
{
cout<<”value of i =”<<i;
}
}
While Loop:
The while loop allows programs to repeat a statement or series of statements, over and over,
as long as a certain test condition is true.
The while loop is an entry-condition loop. If the test condition is FALSE to begin with, the
program never executes the body of the loop.
Syntax:
while(condition)
{
statement(s);
}
statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
Example:
Print value of a 10 times
main ()
{
int a = 10; // Local variable declaration:
while( a < 20 ) // while loop execution
{
cout << "value of a: " << a << endl;
a++;
}
}
Example:
Calculate Sum of Natural Numbers
main()
{ int n, count, sum=0;
cout<<”Enter an integer: "; cin>> n; count=1;
while(count<=n) /* while loop terminates if count>n */
{ sum+=count; /* sum=sum+count */
++count;
}
cout<<”Sum = "<<sum; }
Example:
When a = -1 program will stop
int count = 0, grade;
cout << "Please enter grade ( enter -1 to quit)";
cin >> grade;
while (grade != -1)
{
count++;
cout << "Grade # " << count << " is " << grade << endl;
cout << "Please enter grade ( enter -1 to quit) ";
cin >> grade;
}
While Loop is Known as Entry Controlled Loop because in The while loop first we initialize
the value of variable or Starting point of Execution and then we check the condition and if the
condition is true then it will execute the statements and then after it increments or decrements the
value of a variable. But in the while loop if a Condition is false then it will never Executes the
Statement So that For Execution, this is must that the Condition must be true.
do-while loop:
The do-while loop is similar to the while loop, except that the test condition occurs at the end
of the loop. Having the test condition at the end, guarantees that the body of the loop always
executes at least one time.
The do-while loop is an exit-condition loop. This means that the body of the loop is always
executed first. Then, the test condition is evaluated. If the test condition is TRUE, the
program executes the body of the loop again. If the test condition is FALSE, the loop terminates
and program execution continues with the statement following the while.
Syntax:
do
{
statement(s);
}while( condition );
The conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
Example:
main ()
{
int a = 10;
do
{ cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
}
Example:
char ans;
ENGR. FARHAN AHMED Page 16
Computer Programming Principles
do
{
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N'.\n";
cin >> ans;
}
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
This is Also Called as Exit Controlled Loop we know that in The while loop the condition is
check before the execution of the program but if the condition is not true then it will not execute
the statements so for this purpose we use the do while loop in this first it executes the statements
and then it increments the value of a variable and then last it checks the condition So in this
either the condition is true or not it Execute the statement at least one time.
Nested Loops:
You can use one or more loop inside any another while, for or do-While loop.
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
A nested loop is a loop within a loop, an inner loop within the body of an outer one.
How this works is that the first pass of the outer loop triggers the inner loop, which executes to
completion. Then the second pass of the outer loop triggers the inner loop again. This repeats
until the outer loop finishes. Of course, a break within either the inner or outer loop would
interrupt this process.
The syntax for a nested for loop statement in C++ is as follows.
Syntax:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows:
Syntax:
while(condition)
{
while(condition)
{
ENGR. FARHAN AHMED Page 17
Computer Programming Principles
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows:
Syntax:
do
{
statement(s); // you can put more statements.
do
{
statement(s);
}while( condition );
}while( condition );
main()
{
for (int rows = 0; rows < 2; rows++)
{
for (int col = 0; col < 2; col++)
{
cout << 'x'<< ” “ ;
}
cout<< "\n";
}
}
Output:
xxxxx
xxxxx
4.Triangle:
main()
{
int a,b,c,i,j,k,n;
cout<<"enter the value of n"<<endl;
cin>>n;
for(i=n; i>0; i--)
{
for(j=1; j<i; j++)
{
cout<<" ";
}
for(k=j-1;k<n;k++)
{
cout<<"*"<< " ";
}
cout<<"\n";
}}
Output:
Assignment:
Note: Use for loop in your all programs.
1 Observe the Output of the above example.
2 Make a program to print the table of the user given number.
3 Make a program to print the table of user given number & limit will also be taken from user.
4 Make a program to calculate the factorial of the user given number.
5 Write a program which display Factors of a Number. Hint:factor of 6 is 2, 3.
6 Write a program that will print A to Z alphabets.
7 Write the outputs of following programs:
Write the program code to draw the following shapes using nested for loops.
1 ******* GFEDCBA
12 *****
123 GFEDC
***
1234
12345 * GFE
1234 ***
G
123 *****
ENGR. FARHAN AHMED Page 21
Computer Programming Principles
12 *******
1
Lab # 03
FUNCTIONS IN C++
Objective:
Understanding the use of functions in C++.
A function is a group of statements that is executed when it is called from some point of the
program. The following is its format:
type name ( parameter1, parameter2, ...) { statements }
where:
type is the data type specifier of the data returned by the function.
name is the identifier by which it will be possible to call the function.
parameters (as many as needed): Each parameter consists of a data type specifier followed by
an identifier, like any regular variable declaration (for example: int x) and which acts within the
function as a regular local variable. They allow to pass arguments to the function when it is
called. The different parameters are separated by commas.
statements is the function's body. It is a block of statements surrounded by braces { }.
//function example
#include <iostream>
usingnamespacestd;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout<< "The result is " << z;
return 0;
}
Output:
The result is 8
In order to examine this code, first of all remember something said at the beginning of this
tutorial: a C++ program always begins its execution by the main function. So we will begin
there. We can see how the main function begins by declaring the variable z of type int. Right
after that, we see a call to a function called addition. Paying attention we will be able to see the
similarity between the structure of the call to the function and the declaration of the function
itself some code lines above:
The parameters and arguments have a clear correspondence. Within the main function we called
to addition passing two values: 5 and 3, that correspond to the inta andint b parameters declared
for function addition.
At the point at which the function is called from within main, the control is lost by main and
passed to function addition. The value of both arguments passed in the call (5 and 3) are copied
to the local variables inta andint b within the function. Function addition declares another local
variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b.
Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8
The following line of code:
return (r);
Finalizes function addition, and returns the control back to the function that called it in the first
place (in this case, main). At this moment the program follows its regular course from the same
point at which it was interrupted by the call to addition. But additionally, because the return
statement in function addition specified a value: the content of variable r (return (r);), which at
that moment had a value of 8. This value becomes the value of evaluating the function call.
So being the value returned by a function the value given to the function call itself when it is
evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain
it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by
the value it returns (8).
Example:
#include<iostream>
using namespace std;
int factorial(int n);
int main ()
{
int n1,fact;
cout <<"Enter the number whose factorial has to be calculated" << endl;
cin >> n1;
fact=factorial(n1);
cout << "The factorial of " << n1 << " is : " << fact << endl;
return(0);
}
int factorial(int n)
{
int i=0,fact=1;
if(n<=1)
{
return(1);
}
else
{
for(i=1;i<=n;i++)
{
fact=fact*i;
}
return(fact);
}
}
The result of the program is:-
Imagine that we want to make a function just to show a message on the screen. We do not need it
to return any value. In this case we should use the void type specifier for the function. This is a
special specifier that indicates absence of type.
Output:
I'm a function!
void can also be used in the function's parameter list to explicitly specify that we want the
function to take no actual parameters when it is called.
return 0;
}
Output:
x=2, y=6, z=14
The first thing that should call your attention is that in the declaration of duplicate the type of
each parameter was followed by an ampersand sign (&). This ampersand is what specifies that
their corresponding arguments are to be passed by reference instead of by value.
When a variable is passed by reference we are not passing a copy of its value, but we are
somehow passing the variable itself to the function and any modification that we do to the local
variables will have an effect in their counterpart variables passed as arguments in the call to the
function.
without the ampersand signs (&), we would have not passed the variables by reference, but a
copy of their values instead, and therefore, the output on screen of our program would have been
the values of x, y and z without having been modified.
Passing by reference is also an effective way to allow a function to return more than one
value. For example, here is a function that returns the previous and next numbers of the first
parameter passed.
Output:
Previous=99, Next=101
For example:
// default values in functions
#include <iostream>
usingnamespacestd;
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main ()
{
cout<< divide (12);
cout<<endl;
cout<< divide (20,4);
return 0;
}
Output:
6
5
As we can see in the body of the program there are two calls to function divide. In the first
one:divide(12)
we have only specified one argument, but the function divide allows up to two. So the function
divide has assumed that the second parameter is 2 since that is what we have specified to happen
if this parameter was not passed (notice the function declaration, which finishes with int b=2, not
just int b). Therefore the result of this function call is 6 (12/2). In the second call: divide(20,4)
there are two parameters, so the default value for b (int b=2) is ignored and b takes the value
passed as argument, that is 4, making the result returned equal to 5 (20/4).
Assignment:
1. Practice the above programs.
2. Write a Program to calculate the Greatest Common Divisor.
LAB # 04
Introduction to Array & Multidimensional
Arrays
Objective:
To understand the implementation of 1-dimensional array.
In everyday life we commonly group similar objects into units. We buy peas by the can and eggs
by the carton. In computer languages we also need to group together data items of the same type.
The most basic mechanism that accomplishes this in C++ is the array. Arrays can hold a few
data items or tens of thousands. The data items grouped in an array can be simple types such as
int or float, or they can be user-defined types such as structures and objects. Arrays exist in
almost every computer language. Arrays in C++ are similar to those in other languages, and
identical to those in C.
Array Fundamentals:
A simple example program will serve to introduce arrays. This program, REPLAY, creates an
array of four integers representing the ages of four people. It then asks the user to enter four
values, which it places in the array. Finally, it displays all four values.
// replay.cpp
// gets four ages from user, displays them
#include <iostream>
using namespace std;
int main()
{
int age[4]; //array ‘age’ of 4 ints
Array Elements:
The items in an array are called elements (in contrast to the items in a structure, which are
called members). As we noted, all the elements in an array are of the same type; only the
values vary. Figure 7.2 shows the elements of the array age.
int main()
{
const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 variables
cout << “Enter widget sales for 6 days\n”;
for(int j=0; j<SIZE; j++) //put figures in array
cin >> sales[j];
double total = 0;
for(j=0; j<SIZE; j++) //read figures from array
total += sales[j]; //to find total
double average = total / SIZE; // find average
cout << “Average = “ << average << endl;
return 0;
}
Here’s some sample interaction with SALES:
Enter widget sales for 6 days
352.64
867.70
781.32
867.35
746.21
189.45
Average = 634.11
A new detail in this program is the use of a const variable for the array size and loop limits. This
variable is defined at the start of the listing:
const int SIZE = 6;
Using a variable (instead of a number, such as the 4 used in the last example) makes it easier to
change the array size: Only one program line needs to be changed to change the array size, loop
limits, and anywhere else the array size appears. The all-uppercase name reminds us that the
variable cannot be modified in the program.
Initializing Arrays:
You can give values to each array element when the array is first defined. Here’s an example,
DAYS, that sets 12 array elements in the array days_per_month to the number of days in each
month.
// days.cpp
// shows days from start of year to date specified
#include <iostream>
using namespace std;
int main()
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
ENGR. FARHAN AHMED Page 33
Computer Programming Principles
Actually, we don’t need to use the array size when we initialize all the array elements, since the
compiler can figure it out by counting the initializing variables. Thus we can write int
days_per_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
What happens if you do use an explicit array size, but it doesn’t agree with the number of
initializers? If there are too few initializers, the missing elements will be set to 0. If there are too
many, an error is signaled.
Multi-dimension array
So far we’ve looked at arrays of one dimension: A single variable specifies each array element.
But arrays can have higher dimensions. Here’s a program, SALEMON, that uses a two-
dimensional array to store sales figures for several districts and several months:
// salemon.cpp
// displays sales chart using 2-d array
#include <iostream>
#include <iomanip> //for setprecision, etc.
using namespace std;
const int DISTRICTS = 4; //array dimensions
const int MONTHS = 3;
int main()
{
int d, m;
double sales[DISTRICTS][MONTHS]; //two-dimensional array
//definition
cout << endl;
for(d=0; d<DISTRICTS; d++) //get array values
for(m=0; m<MONTHS; m++)
{
cout << “Enter sales for district “ << d+1;
cout << “, month “ << m+1 << “: “;
cin >> sales[d][m]; //put number in array
}
cout << “\n\n”;
cout << “ Month\n”;
cout << “ 1 2 3”;
for(d=0; d<DISTRICTS; d++)
{
cout <<”\nDistrict “ << d+1;
for(m=0; m<MONTHS; m++) //display array values
cout << setiosflags(ios::fixed) //not exponential
<< setiosflags(ios::showpoint) //always use point
<< setprecision(2) //digits to right
<< setw(10) //field width
<< sales[d][m]; //get number from array
} //end for(d)
cout << endl;
return 0;
} //end main
This program accepts the sales figures from the user and then displays them in a table.
int main()
{
int d, m;
//initialize array elements
double sales[DISTRICTS][MONTHS]
= { { 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 },
{ 12838.29, 2332.63, 32.93 } };
cout << “\n\n”;
cout << “ Month\n”;
cout << “ 1 2 3”;
for(d=0; d<DISTRICTS; d++)
{
cout <<”\nDistrict “ << d+1;
for(m=0; m<MONTHS; m++)
cout << setw(10) << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint) << setprecision(2)
<< sales[d][m]; //access array element
}
cout << endl;
return 0;
}
Remember that a two-dimensional array is really an array of arrays. The format for initializing
such an array is based on this fact. The initializing values for each sub-array are enclosed in
braces and separated by commas { 1432.07, 234.50, 654.01 } and then all four of these sub-
arrays, each of which is an element in the main array, is likewise enclosed by braces and
separated by commas, as can be seen in the listing.
Assignment:
a) Write a statement that defines an array coins of type int and initializes it to the value of
the penny, nickel, dime, quarter, half-dollar, and dollar.
c) Make a program in which store building information in array e.g. rooms, windows, doors.
d) Make a program using multidimensional array to save guest house building record.
e) Practice all above programs and take output of the above program.
LAB # 05
Arrays can be used as arguments to functions. Here’s an example, a variation of the SALEINIT
program, that passes the array of sales figures to a function whose purpose is to display the data
as a table. Here’s the listing for SALEFUNC:
// salefunc.cpp
// passes array as argument
#include <iostream>
#include <iomanip> //for setprecision, etc.
using namespace std;
const int DISTRICTS = 4; //array dimensions
const int MONTHS = 3;
void display( double[DISTRICTS][MONTHS] ); //declaration
//--------------------------------------------------------------
int main()
{ //initialize two-dimensional array
double sales[DISTRICTS][MONTHS]
= { { 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 },
{ 12838.29, 2332.63, 32.93 } };
display(sales); //call function; array as argument
cout << endl;
return 0;
} //end main
//--------------------------------------------------------------
//display()
//function to display 2-d array passed as argument
void display( double funsales[DISTRICTS][MONTHS] )
{
int d, m;
cout << “\n\n”;
cout << “ Month\n”;
cout << “ 1 2 3”;
for(d=0; d<DISTRICTS; d++)
{
ENGR. FARHAN AHMED Page 39
Computer Programming Principles
Assignment:
a) Start with a program that allows the user to input a number of integers, and then stores
them in an int array. Write a function called maxint() that goes through the array, element
by element, looking for the largest one. The function should take as arguments the
address of the array and the number of elements in it, and return the index number of the
largest element. The program should call this function and then display the largest
element and its index number.
LAB # 06
C-String Variables
Objective:
TO understand the use of C-string variable in C++.
As with other data types, strings can be variables or constants. Here’s an example that defines a
single string variable. (In this section we’ll assume the word string refers to a C-string.) It asks
the user to enter a string, and places this string in the string variable. Then it displays the string.
Here’s an example that defines a single string variable. (In this section we’ll assume the word
string refers to a C-string.) It asks the user to enter a string, and places this string in the string
variable. Then it displays the string. Here’s the listing for STRINGIN:
// stringin.cpp
// simple string variable
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
cout << “Enter a string: “;
cin >> str; //put string in str
//display string from str
cout << “You entered: “ << str << endl;
return 0;
}
// safetyin.cpp
ENGR. FARHAN AHMED Page 42
Computer Programming Principles
String Constants:
// strinit.cpp
// initialized string
#include <iostream>
using namespace std;
int main()
{
char str[] = “Farewell! thou art too dear for my possessing.”;
cout << str << endl;
return 0;
}
Enter a string:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty’s orient deep
These flowers, as in their causes, sleep.
$
You entered:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty’s orient deep
These flowers, as in their causes, sleep.
We terminate each line with Enter, but the program continues to accept input until we
enter ‘$’.
*) Write the name of all string functions and give its short description.
ENGR. FARHAN AHMED Page 45
Computer Programming Principles
LAB # 07
Structures
Objective:
To understand the concept of structures , Nested Structures and its implementation in C++.
Introduction to structures:
A structure is a collection of simple variables. The variables in a structure can be of different
types: Some can be int, some can be float, and so on. (This is unlike the array, in which all the
variables must be the same type.) The data items in a structure are called the members of the
structure.
A Simple Structure:
Let’s start off with a structure that contains three variables: two integers and a floating-point
number. This structure represents an item in a widget company’s parts inventory. The structure is
a kind of blueprint specifying what information is necessary for a single part. The company
makes several kinds of widgets, so the widget model number is the first member of the structure.
ENGR. FARHAN AHMED Page 46
Computer Programming Principles
The number of the part itself is the next member, and the final member is the part’s cost.
The program PARTS defines the structure part, defines a structure variable of that type called
part1, assigns values to its members, and then displays these values.
Example:
////////////////////////////////////////////////////////////////
struct part //declare a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
////////////////////////////////////////////////////////////////
int main()
{
part part1; //define a structure variable
part1.modelnumber = 6244; //give values to structure members
part1.partnumber = 373;
part1.cost = 217.55F;
//display structure members
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
return 0;
}
Output:
The program’s output looks like this:
Model 6244, part 373, costs $217.55
Nested Structures:
You can nest structures within other structures. Here’s a variation on the program that shows
how this looks. In this program we want to create a data structure that stores the dimensions of a
typical room: its length and width. Since we’re working with English distances, we’ll use two
variables of type Distance as the length and width variables.
struct Room
{
Distance length;
Distance width;
}
Let’s examine a different kind of example. This one uses a structure to model a playing card. The
program imitates a game played by cardsharps (professional gamblers) at carnivals. The
cardsharp shows you three cards, then places them face down on the table and interchanges their
positions several times. If you can guess correctly where a particular card is, you win. Everything
is in plain sight, yet the cardsharp switches the cards so rapidly and confusingly that the player
(the mark) almost always loses track of the card and loses the game, which is, of course, played
for money.
Here’s the structure the program uses to represent a playing card:
struct card
{
int number;
int suit;
};
This structure uses separate members to hold the number of the card and the suit. The number
runs from 2 to 14, where 11, 12, 13, and 14 represent the jack, queen, king, and ace, respectively
(this is the order used in poker). The suit runs from 0 to 3, where these four numbers represent
clubs, diamonds, hearts, and spades.
Here’s the listing for CARDS:
// cards.cpp
// demonstrates structures using playing cards
#include <iostream>
using namespace std;
const int clubs = 0; //suits
const int diamonds = 1;
const int hearts = 2;
const int spades = 3;
const int jack = 11; //face cards
const int queen = 12;
const int king = 13;
const int ace = 14;
////////////////////////////////////////////////////////////////
struct card
{
int number; //2 to 10, jack, queen, king, ace
int suit; //clubs, diamonds, hearts, spades
};
////////////////////////////////////////////////////////////////
int main()
{
card temp, chosen, prize; //define cards
int position;
card card1 = { 7, clubs }; //initialize card1
Output:
Here’s some sample interaction with the program:
Card 1 is the 7 of clubs
Card 2 is the jack of hearts
Card 3 is the ace of spades
I’m swapping card 1 and card 3
I’m swapping card 2 and card 3
I’m swapping card 1 and card 2
Now, where (1, 2, or 3) is the ace of spades? 3
Sorry. You lose.
Exercises:
A phone number, such as (212) 767-8900, can be thought of as having three parts: the area code
(212), the exchange (767), and the number (8900). Write a program that uses a structure to store
these three parts of a phone number separately. Call the structure phone. Create two structure
variables of type phone. Initialize one, and have the user input a number for the other one. Then
display both numbers. The interchange might look like this:
Enter your area code, exchange, and number: 415 555 1212
My number is (212) 767-8900
Your number is (415) 555-1212
a. Create a structure called Volume that uses three variables of type Distance to model the
volume of a room. Initialize a variable of type Volume to specific dimensions, then calculate
the volume it represents, and print out the result.
To calculate the volume, convert each dimension from a Distance variable to a variable of
type float representing feet and fractions of a foot, and then multiply the resulting three
numbers.
b. Create a structure called employee that contains two members: an employee number
(type int) and the employee’s compensation (in dollars; type float). Ask the user to fill in
this data for three employees, store it in three variables of type nested struct employee, and
then display the information for each employee.
LAB # 08
Arrays of Structures
Objective:
To understand the use of arrays in structures.
Arrays can contain structures as well as simple data types. Here’s an example based on the part
structure from last lab, “Structures.”
// partaray.cpp
// structure variables as array elements
#include <iostream>
using namespace std;
const int SIZE = 4; //number of parts in array
////////////////////////////////////////////////////////////////
struct part //specify a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
////////////////////////////////////////////////////////////////
int main()
{
int n;
part apart[SIZE]; //define array of structures
for(n=0; n<SIZE; n++) //get values for all members
{
cout << endl;
cout << “Enter model number: “;
cin >> apart[n].modelnumber; //get model number
cout << “Enter part number: “;
cin >> apart[n].partnumber; //get part number
cout << “Enter cost: “;
cin >> apart[n].cost; //get cost
}
cout << endl;
for(n=0; n<SIZE; n++) //show values for all members
{
cout << “Model “ << apart[n].modelnumber;
ENGR. FARHAN AHMED Page 52
Computer Programming Principles
This has the same syntax as that of arrays of simple data types. Only the type name, part, shows
that this is an array of a more complex type. Accessing a data item that is a member of a
structure that is itself an element of an array
involves a new syntax. For example
apart[n].modelnumber
refers to the modelnumber member of the structure that is element n of the apart array.
Arrays of structures are a useful data type in a variety of situations. We’ve shown an array of car
parts, but we could also store an array of personnel data (name, age, salary), an array of
geographical data about cities (name, population, elevation), and many other types of data.
Assignment:
In the game of contract bridge, each of four players is dealt 13 cards, thus exhausting the entire
deck. After shuffling the deck, it deals four hands of 13 cards each. Each of the four players’
hands should then be displayed.
LAB # 09
The Standard C++ string Class
Objective:
To understand the standard C++ string Class and its implementation on different compiler
e.g. Dev-C++, Visual Studio.
Standard C++ includes a new class called string. This class improves on the traditional Cstring in
many ways. For one thing, you no longer need to worry about creating an array of the right size
to hold string variables. The string class assumes all the responsibility for memory management.
Also, the string class allows the use of overloaded operators, so you can concatenate string
objects with the + operator:
s3 = s1 + s2
//sstrass.cpp
//defining and assigning string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Man”); //initialize
string s2 = “Beast”; //initialize
string s3;
s3 = s1; //assign
cout << “s3 = “ << s3 << endl;
s3 = “Neither “ + s1 + “ nor “; //concatenate
s3 += s2; //concatenate
cout << “s3 = “ << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << “ nor “ << s2 << endl;
return 0;
}
n = s1.find_first_of(“spde”);
cout << “First of spde at “ << n << endl;
n = s1.find_first_not_of(“aeiouAEIOU”);
cout << “First consonant at “ << n << endl;
return 0;
}
#include <string>
using namespace std;
int main()
{
string aName = “George”;
string userName;
cout << “Enter your first name: “;
cin >> userName;
if(userName==aName) //operator ==
cout << “Greetings, George\n”;
else if(userName < aName) //operator <
cout << “You come before George\n”;
else
cout << “You come after George\n”;
//compare() function
int n = userName.compare(0, 2, aName, 0, 2);
cout << “The first two letters of your name “;
if(n==0)
cout << “match “;
else if(n < 0)
cout << “come before “;
else
cout << “come after “;
cout << aName.substr(0, 2) << endl;
return 0;
}
Questions:
1) A string in C++ is an _________ of type _________.
2) True or false: The extraction operator (>>) stops reading a string when it encounters a space.
3) You can read input that consists of multiple lines of text using
Exercise:
*) Write a function called reversit() that reverses a C-string (an array of char). Use a for loop that
swaps the first and last characters, then the second and next-to-last characters, and so on. The
string should be passed to reversit() as an argument.
Write a program to exercise reversit(). The program should get a string from the user, call
reversit(), and print out the result. Use an input method that allows embedded blanks. Test the
program with Napoleon’s famous phrase, “Able was I ere I saw Elba.”
Lab # 10
Introduction to Pointers
Pointers :
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. Pointers improve execution time and saves space.
Pointer points to a particular data type.
Pointers declarations :
Pointer Operators :
There are two important pointer operators such as ‘*’ and ‘&’.
• The ‘&’ is a address operator/unary operator. The unary operator returns the address of the
memory where a variable is located.
• The ‘*’ operator is called the value at address operator/ indirection operator. It returns the
contents of the memory location pointed to. The indirection operator is also called deference operator.
Example 1:
main()
{
char c, *cc;
int i,*ii;
float a,*aa;
c=’a’;
i=54;
a=3.14;
cc=&c;
ii=&i;
aa=&a;
cout<<cc;
cout<<ii;
cout<<aa;
cout<<*cc;
cout<<*ii;
cout<<*aa;
}
The program defines variables of different types and pointers to it. In the end it prints the values
and the addresses.
In order to have a pointer actually point to another variable it is necessary to have the memory
address of that variable also. To get the memory address of a variable (its location in memory),
put the & sign in front of the variable name. This makes it give its address. This is called the
address-of operator, because it returns the memory address. Conveniently, both ampersand and
address-of start with a; that's a useful way to remember that you use & to get the address of a
variable.
Example 2:
#include <iostream.h>
int main()
{
int x; // A normal integer
int *p; // A pointer to an integer
Passing an argument by address involves passing the address of the argument variable rather than
the argument variable itself. Because the argument is an address, the function parameter must be
a pointer. The function can then dereference the pointer to access or change the value being
pointed to.
In C, arguments are passed to functions by value; i.e. only the values of argument expressions are passed
to the called function. Some programming languages allow arguments passed by reference, which allows
the called function to make changes in argument objects. C allows only call by value, not call by
reference; however, if a called function is to change the value of an object defined in the calling function,
it can be passed a value which is a pointer to the object. The called function can then dereference the
pointer to access the object indirectly. We have also seen that a C function can return a single value as the
value of the function. However, by indirect access, a called function can effectively ``return'' several
values. Only one value is actually returned as the value of the function, all other values may be indirectly
stored in objects in the calling function. This use of pointer variables is one of the most common in C. Let
us look at some simple examples that use indirect access.
Example:
int main()
{
int nValue = 5;
OUTPUT;
nValue = 5
nValue = 6
The program passes the address of a variable to a function that changes its original value.
Exercises:
a. Write a program that will declare variables of each type and pointers to it. Print all
values and addresses.
b. Write a program that will pass the length and breadth and calculate the area and
perimeter.
c. Try to write the above program without using pointers. Where does the issue arise?
Lab # 11
Pointers and Arrays
We have seen in our study of functions and arrays that in order to pass an array to a function we
would have to pass each individual element separately. In this lab, we will see how to pass an
entire array at once with the help of pointers.
In C, the name of the array (without the subscript) itself is a pointer. For example, consider the statement
int list[24];
fun (list, 2);
Here, the value passes to the function fun() is the address of the first element of the array list.
2 3 4 5 6
2222 2224 2226 2228 2230
List
Consequently, if we print *list, the value that will be printed is the value 2, and for *(list + 1), the value 3,
for *(list + 2) the value 4, and so on and so forth.
Example:
#include <iostream.>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
return avg;
}
The program passes the address of an array and the size to a function which calculates its
average and returns the result.
Exercises:
a. Write a program that will pass an array to a function that will add 5 to each element of
the array.
b. Write a program that passes an array “marks” of 6 subjects to a function that calculates
the percentage.
Lab # 12
Enumerations
A different approach to defining your own data type is the enumeration. OR
An enum declaration defines the set of all names that will be permissible values of the type.
These permissible values are called enumerators.
An enumeration is a list of all possible values. This is unlike the specification of an int, for
example, which is given in terms of a range of values. In an enum you must give a specific name
to every possible value.
// dayenum.cpp
// demonstrates enum types
#include <iostream>
using namespace std;
//specify enum type
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main()
{
days_of_week day1, day2; //define variables
day1 = Mon; //give values to
// demonstrates enumerations
#include <iostream>
using namespace std;
const int jack = 11; //2 through 10 are unnamed integers
const int queen = 12;
const int king = 13;
const int ace = 14;
enum Suit { clubs, diamonds, hearts, spades };
////////////////////////////////////////////////////////////////
struct card
{
int number; //2 to 10, jack, queen, king, ace
Suit suit; //clubs, diamonds, hearts, spades
};
////////////////////////////////////////////////////////////////
int main()
{
chosen.suit == prize.suit)
cout << “That’s right! You win!\n”;
else
cout << “Sorry. You lose.\n”;
return 0;
}
Example: 02
Our next example counts the words in a phrase typed in by the user. Unlike the earlier
CHCOUNT example, however, it doesn’t simply count spaces to determine the number of
words.
Instead it counts the places where a string of nonspace characters changes to a space.
// wdcount.cpp
// demonstrates enums, counts words in phrase
#include <iostream>
using namespace std;
#include <conio.h> //for getche()
enum itsaWord { NO, YES }; //NO=0, YES=1
int main()
{
itsaWord isWord = NO; //YES when in a word,
//NO when in whitespace
char ch = ‘a’; //character read from keyboard
int wordcount = 0; //number of words read
cout << “Enter a phrase:\n”;
do {
ch = getche(); //get character
if(ch==’ ‘ || ch==’\r’) //if white space,
{
if( isWord == YES ) //and doing a word,
{ //then it’s end of word
wordcount++; //count the word
isWord = NO; //reset flag
}
} //otherwise, it’s
else //normal character
if( isWord == NO ) //if start of word,
isWord = YES; //then set flag
} while( ch != ‘\r’ ); //quit on Enter key
cout << “\n---Word count is “ << wordcount << “---\n”;
return 0;
}
Exercises:
a. We said earlier that C++ I/O statements don’t automatically understand the data types
of enumerations. Instead, the (>>) and (<<) operators think of such variables simply as
integers.
You can overcome this limitation by using switch statements to translate between
the user’s way of expressing an enumerated variable and the actual values of the
enumerated variable. For example, imagine an enumerated type with values that indicate
an employee type within an organization:
enum etype { laborer, secretary, manager, accountant, executive,
researcher };
Write a program that first allows the user to specify a type by entering its first letter
(‘l’, ‘s’, ‘m’, and so on), then stores the type chosen as a value of a variable of type
enum etype, and finally displays the complete word for this type.
Enter employee type (first letter only)
laborer, secretary, manager,
accountant, executive, researcher): a
Employee type is accountant.
You’ll probably need two switch statements: one for input and one for output.
Lab # 13
Writing Data:
The following program writes a character, an integer, a type double, and two string objects to a
disk file. There is no output to the screen. Here’s the listing for FORMATO:
// formato.cpp
// writes formatted output to a file, using <<
#include <fstream> //for file I/O
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch = ‘x’;
int j = 77;
double d = 6.02;
string str1 = “Kafka”; //strings without
string str2 = “Proust”; // embedded spaces
ofstream outfile(“fdata.txt”); //create ofstream object
outfile << ch //insert (write) data
<< j
<< ‘ ‘ //needs space between numbers
<< d
<< str1
<< ‘ ‘ //needs spaces between strings
<< str2;
cout << “File written\n”;
return 0;
}
Reading Data:
We can read the file generated by FORMATO by using an ifstream object, initialized to the
name of the file. The file is automatically opened when the object is created. We can then read
from it using the extraction (>>) operator.
Here’s the listing for the FORMATI program, which reads the data back in from the
FDATA.TXT
file:
// formati.cpp
// reads formatted output from a file, using >>
#include <fstream> //for file I/O
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
int j;
double d;
string str1;
string str2;
ifstream infile(“fdata.txt”); //create ifstream object
//extract (read) data from it
infile >> ch >> j >> d >> str1 >> str2;
cout << ch << endl //display the data
<< j << endl
ENGR. FARHAN AHMED Page 70
Computer Programming Principles
// oline.cpp
// file output with strings
#include <fstream> //for file I/O
using namespace std;
int main()
{
ofstream outfile(“TEST.TXT”); //create file for output
//send text to file
outfile << “I fear thee, ancient Mariner!\n”;
outfile << “I fear thy skinny hand\n”;
outfile << “And thou art long, and lank, and brown,\n”;
outfile << “As is the ribbed sea sand.\n”;
return 0;
// iline.cpp
// file input with strings
#include <fstream> //for file functions
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80; //size of buffer
char buffer[MAX]; //character buffer
ifstream infile(“TEST.TXT”); //create file for input
while( !infile.eof() ) //until end-of-file
{
infile.getline(buffer, MAX); //read a line of text
cout << buffer << endl; //display it
}
ENGR. FARHAN AHMED Page 71
Computer Programming Principles
return 0;
}
Character I/O:
The put() and get() functions, which are members of ostream and istream, respectively, can be
used to output and input single characters. Here’s a program, OCHAR, that outputs a string,one
character at a time.
// ochar.cpp
// file output with characters
#include <fstream> //for file functions
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = “Time is a great teacher, but unfortunately “
“it kills all its pupils. Berlioz”;
ofstream outfile(“TEST.TXT”); //create file for output
for(int j=0; j<str.size(); j++) //for each character,
outfile.put( str[j] ); //write it to file
cout << “File written\n”;
return 0;
}
// ichar.cpp
// file input with characters
#include <fstream> //for file functions
#include <iostream>
using namespace std;
int main()
{
char ch; //character to read
ifstream infile(“TEST.TXT”); //create file for input
while( infile ) //read until EOF or error
{
infile.get(ch); //read character
cout << ch; //display it
}
cout << endl;
return 0;
}
ENGR. FARHAN AHMED Page 72
Computer Programming Principles
Character I/O:
Another approach to reading characters from a file is the rdbuf() function, a member of the ios
class. This function returns a pointer to the streambuf (or filebuf) object associated with the
stream object. This object contains a buffer that holds the characters read from the stream, so you
can use the pointer to it as a data object in its own right. Here’s the listing for ICHAR2:
// ichar2.cpp
// file input with characters
#include <fstream> //for file functions
#include <iostream>
using namespace std;
int main()
{
ifstream infile(“TEST.TXT”); //create file for input
cout << infile.rdbuf(); //send its buffer to cout
cout << endl;
return 0;
}
This program has the same effect as ICHAR. It also takes the prize for the shortest file oriented
program. Note that rdbuf() knows that it should return when it encounters an EOF.
Binary I/O:
You can write a few numbers to disk using formatted I/O, but if you’re storing a large amount of
numerical data it’s more efficient to use binary I/O, in which numbers are stored as they are in
the computer’s RAM memory, rather than as strings of characters. In binary I/O an int is stored
in 4 bytes, whereas its text version might be “12345”, requiring 5 bytes. Similarly, a float is
always stored in 4 bytes, while its formatted version might be “6.02314e13”, requiring 10 bytes.
Our next example shows how an array of integers is written to disk and then read back into
memory, using binary format. We use two new functions: write(), a member of ofstream; and
read(), a member of ifstream. These functions think about data in terms of bytes (type char).
They don’t care how the data is formatted, they simply transfer a buffer full of bytes from and to
a disk file. The parameters to write() and read() are the address of the data buffer and its length.
The address must be cast, using reinterpret_cast, to type char*, and the length is the length in
bytes (characters), not the number of data items in the buffer. Here’s the listing for BINIO:
// binio.cpp
// binary input and output with integers
#include <fstream> //for file streams
#include <iostream>
using namespace std;
You must use the ios::binary argument in the second parameter to write() and read() when
working with binary data.
//open it
os.open(“a:edata.dat”, ios::trunc | ios::binary);
if(!os)
{ cerr << “Could not open output file\n”; exit(1); }
cout << “Writing...\n”; //write buffer to it
os.write( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!os)
{ cerr << “Could not write to file\n”; exit(1); }
os.close(); //must close it
for(j=0; j<MAX; j++) //clear buffer
buff[j] = 0;
ifstream is; //create input stream
is.open(“a:edata.dat”, ios::binary);
if(!is)
{ cerr << “Could not open input file\n”; exit(1); }
cout << “Reading...\n”; //read file
is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!is)
{ cerr << “Could not read from file\n”; exit(1); }
for(j=0; j<MAX; j++) //check data
if( buff[j] != j )
{ cerr << “\nData is incorrect\n”; exit(1); }
cout << “Data is correct\n”;
return 0;
}
Analyzing Errors:
In the REWERR example we determined whether an error occurred in an I/O operation by
examining the return value of the entire stream object.
if(!is)
// error occurred
// ferrors.cpp
// checks for errors opening file
#include <fstream> // for file functions
#include <iostream>
using namespace std;
int main()
{
ifstream file;
file.open(“a:test.dat”);
if( !file )
// ostrstr.cpp
// writes formatted data into memory
#include <strstream>
#include <iostream>
#include <iomanip> //for setiosflags()
using namespace std;
const int SIZE = 80; //size of memory buffer
int main()
{
char ch = ‘x’; //test data
int j = 77;
double d = 67890.12345;
char str1[] = “Kafka”;
char str2[] = “Freud”;
char membuff[SIZE]; //buffer in memory
ostrstream omem(membuff, SIZE); //create stream object
omem << “ch=” << ch << endl //insert formatted data
<< “j=” << j << endl //into object
<< setiosflags(ios::fixed) //format with decimal point
<< setprecision(2) //two digits to right of dec
<< “d=” << d << endl
<< “str1=” << str1 << endl
<< “str2=” << str2 << endl
When you run the program, membuff will be filled with the formatted text:
ch=x\nj=77\nd=67890.12\nstr1=Kafka\nstr2=Freud\n\0
Question:
1) A C++ stream is
a. the flow of control through a function.
b. a flow of data from one place to another.
c. associated with a particular class.
d. a file.
2) To write data that contains variables of type float to an object of type ofstream, you should use
a. the insertion operator.
b. seekg().
c. write().
d. put().
3) True or false: A file pointer always contains the address of the file.
4) The statement
f1.write( (char*)&obj1, sizeof(obj1) );
a. writes the member functions of obj1 to f1.
b. writes the data in obj1 to f1.
c. writes the member functions and the data of obj1 to f1.
d. writes the address of obj1 to f1.
Exercise:
1) In a loop, prompt the user to enter name data consisting of a first name, middle initial,
last name, and employee number (type unsigned long). Then, using formatted I/O with
the insertion (<<) operator, write these four data items to an ofstream object. Don’t forget
ENGR. FARHAN AHMED Page 77
Computer Programming Principles
that strings must be terminated with a space or other whitespace character. When the user
indicates that no more name data will be entered, close the ofstream object, open an
ifstream object, read and display all the data in the file, and terminate the program.
2) Add error checking to the extraction (>>) operator. With error checking it’s probably
better to prompt for the first fraction, then for the operator, and then for the second
fraction, rather than using a single statement. This makes the format more
comprehensible when it is interspersed with error messages.
Lab # 14
Graphics Application
Graphics Applications:
• For most of this course, we deal with text based console applications (cin / cout).
• For just one week, we’re going to look at graphics applications which display simple shapes in
the graphics window, not the console.
• So our commands will be quite different.
For example, use cwin instead of cout.
cout << my_circle; //Does not draw a circle.
cwin << my_circle; //Draws a circle.
• We don’t need the std namespace, because we’re not using the standard libraries.
# include “ccc_win.h”
int ccc_win_main ( ) {
** YOUR CODE HERE **
return 0;
}
Exercise
click.cpp:
# include "ccc_win.h"
int ccc_win_main( ) {
string name = cwin.get_string ("Enter your name: ");
Circle c ( Point(0,0), 1);
cwin << c;
Point m = cwin.get_mouse ("Click inside the circle.");
cwin << m
<< Message (m, name + ", you clicked here.");
return 0;
}
The Point Class: Exercise : Scatterplot the function y = 2x2 for -2<x<2.
The message class: Exercise: Display a digital clock showing the current time.
The Viewing Window: Exercise Scatterplot the curve y = 100 sin(x/3) for 0<x<5.
Lab # 15
Python is Interpreted: Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Features of Python
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
ENGR. FARHAN AHMED Page 84
Computer Programming Principles
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the
X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
The most up-to-date and current source code, binaries, documentation, news, etc., is available on
the official website of Python:
http://www.python.
org/.
You can download Python documentation from
www.python.org/do
c/.
The documentation is available in HTML, PDF, and PostScript formats.
Mac OS X and Linux comes pre-installed with python.
This will install all the necessary dependencies for the notebook, qtconsole, tests etc.
Installing all the necessary libraries might prove troublesome. Anaconda and Canopy
comes prepackaged with all the necessary python libraries and also IPython.
Anaconda
Download Anaconda from https://www.continuum.io/downloads
Anaconda is completely free and includes more than 300 python packages. Both python 2.7 and
3.4 options are available.
Canopy
ENGR. FARHAN AHMED Page 85
Computer Programming Principles
License
This work is licensed under the Creative Commons Attribution 3.0 Unsorted License. To
view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/
The Jupyter Notebook App can be launched by clicking on the Jupyter Notebook icon
installed by Anaconda in the start menu (Windows) or by typing in a terminal (cmd on
Windows):
jupyter notebook
This will launch a new browser window (or a new tab) showing the Notebook Dashboard, a
sort of control panel that allows (among other things) to select which notebook to open.
When started, the Jupyter Notebook App can access only files within its start-up folder
(including any sub-folder). If you store the notebook documents in a subfolder of your
user folder no configuration is necessary. Otherwise, you need to choose a folder which
will contain all the notebooks and set this as the Jupyter Notebook App start-up folder.
Shut down the Jupyter Notebook App
In a nutshell, closing the browser (or the tab) will not close the Jupyter Notebook App. To
completely shut it down you need to close the associated terminal.
In more detail, the Jupyter Notebook App is a server that appears in your browser at a default
address (http://localhost:8888). Closing the browser will not shut down the server. You
can reopen the previous address and the Jupyter Notebook App will be redisplayed.
You can run many copies of the Jupyter Notebook App and they will show up at a similar
address (only the number after ”:”, which is the port, will increment for each new copy).
Since with a single Jupyter Notebook App you can already open many notebooks, we do not
recommend running multiple copies of Jupyter Notebook App.