CS 101B C++ Lab Manual
CS 101B C++ Lab Manual
C++ Programming
Lab manual
Prepared by:
Dr. Iyad Abu Douh, Ahmed Bani-Hani, Fatima Abu-Hawas,
Siba Shaher, Asma Alhami, Enas Abdelrazak,
Reham Abdelqader, Maisaa Khazaleh, Nahed Mansour,
Wafaa Qarqaz, Amal Abu Naser, Ikdam Alhami
Table of Contents
Lab 1: Use the Visual studio environment and Debugging the Code. ...... 3
Lab 2: Use the arithmetic operations and if/else selection structure. ... 11
Lab 3 Classes and Objects .............................................................. 18
Lab 4 Separating class interface from its implementation and data
validation. ..................................................................................... 30
Lab 5 More about selection structures( if and switch statements). ...... 36
Lab 6 Control Structures: while , do-while and for Loop ................... 46
Lab 7 Using Functions .................................................................... 50
Lab 8 Random numbers, scope rules, and default Arguments ............ 55
Lab 9 Function Overloading and recursion ....................................... 60
Lab 10 Arrays ................................................................................ 65
Lab 11 Using Pointers ..................................................................... 70
Lab 12 Using files. ......................................................................... 73
Learn the student, how to open the Microsoft visual c++ 6.0 , and use it to write
and execute a simple program that print a simple statement.
Find and correct the errors.
Applying the escape characters like \n, \t,\r,\a.
Using the single line and multiline comments.
Background:
The student should know the structure of a simple c++ program, in that, any program may
be written according to the following format:
#include<iostream>
using namespace std;
void main()
{
//Program body
}
Also the student should know the meaning for each one of the escape characters:
\n : new line
\t : tab space
\a: alarm
\r: return the cursor to the first character in the same line.
Pre-lab:
Learn the basic structure for a simple c++ program
Learn the function of the escape characters and who to use them.
Know the syntax for writing comments in the program.
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
Lab Assignments:
Lab assignment-1
Learn the student how to open Microsoft visual c++ 6.0 :
Click on the Start button.
Choose all programs.
Then choose Microsoft visual c++ 6.0 as shown in figure 1.
Figure 1
Then you will see a new window that enables you to open a file and write a new program as
shown in figure 2.
Figure 2
From the file menu choose new, a new window will appear as shown in figure 3.
Figure 3
Click on the tab project, choose win32 console application, specify a name for the project,
and then click on the button ok.
From the window appears chooses an empty project then click on finish as shown in figure4.
Figure 4
After that, from the file menu choose new , from the new window click on the tab file,
choose c++ source file, then click on ok as shown in figure 5.
Figure 5
Lab assignment-2
Use the Microsoft visual c++ 6.0 to write the following code.
void main()
{
cout << "Welcome to the wonderful world of C++!!!\n";
}
8
In order to compile this code, from the menu build choose build as shown in figure6.
Figure 6
If the program has any error, this error will be list in the window, and you can correct it. To
be able to execute your program, you should correct all the errors.
In order to run your program, from the menu build choose execute, a new window will
appear like figure7.
Lab assignment-3
What is/are the output for the following code:
#include <iostream>
using namespace std;
void main()
{
cout << "Welcome to the wonderful world of C++!!!\n";
Lab Problems:
Lab Problem-1
Write a program to print the following text:
Hello in my university
(empty line)
Im a student in it faculty
(empty line)
Welcome.
Lab Problem -2
Find and correct the errors in the following code.
#include <iostream>
void main()
{
cout << "we are happy"
Lab Problem -3
10
Background:
11
If Statement:
o Condition
Expression can be either true or false
Can be formed using equality or relational operators
o if statement
If the condition is true, the body of the if statement executes
If the condition is false, the body of the if statement does not
execute
If (
Condition
Statement(s);
12
Pre-lab:
The student should know the structure of a simple C++ program, in that, any program may
be written according to the following format:
#include<iostream>
using namespace std;
void main()
{
//Program body
}
Assessment tools:
13
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
Lab Assignments:
Lab assignment-1
Rewrite the following expression in C++ Code and print it.
Lab assignment-2
Read an integer number of a fixed length (3 digits) from the standard input then print its
digits separated by spaces. For example if 364 is the input then the output should be 3 6 4 or
463
Hint: Use division and modulus operator.
#include<iostream>
using namespace std;
14
void main( )
{
int x;
cin>>x;
1- Main body
2- If body
3- If condition
{
cout<<x%10<<" ";
x=x/10;
cout<<x%10<<" ";
x=x/10;
cout<<x%10<<" ";
x=x/10;
}
}
Lab assignment-3
Write a program to read three integer numbers then find and print the largest one
among these numbers.
#include<iostream>
using namespace std;
void main(
{
int x;
cin>>x;
int y;
15
cin>>y;
int z;
cin>>z;
int max=x;
if(max<y)
max=y;
if(max<z)
max=z;
cout<<"The Max Value is:"<<max<<endl;
}
Lab Problems:
Lab Problem-1:
Read an integer number of a fixed length (4 digits) from the standard input then print the
sum of the odd digits.
Lab Problem -2
Fill in the blank in the following code; what should the program print? based on
the conditions in the programs that check the x variable value:
#include<iostream>
using namespace std;
void main(
{
int x;
cin>>x;
if(x>=0)
{
cout<<"x value is...... "<<endl;
if( x%2==0)
{
cout<<"x value is...... "<<endl;
if( x>999 & x<10000)
{
cout<<"x value contains ....digits
"<<endl;
16
}
}
}
Lab Problem -3
Body Mass Index Calculator (BMI) calculator formulas for calculating BMI is:
Create a BMI calculator application that reads the users weight and height then calculates
and displays the users body mass index.
17
Discover classes
Complete a C++ classes. Class definitions include member access specifiers, member
functions, constructors, and data members.
Perform Object construction
Control access to object data members and member functions by using the private
member access specifiers.
To appreciate the value of object orientation.
Background:
No general back ground needed for this lab.
Pre-labs:
1. Review how to define a variable of type string.
2. Quick review for the class definition, the constructor, and the class members.
Lab
PURPOSE: Prints out generic greeting from vacation spot of choice
class Postcard
{
public:
void print()
{ cout << "Dear " << to_string << ", \n";
cout << "Weather's great, Wish you were here !" << "\n\n";
cout << "See you soon," << "\n";
cout << from_string << ".\n";
}
};
Study the Postcard class, and then do the following:
18
Lab
The following is a class called Rectangle which contains two private data elements ,
Width and Height of type double and a number of member functions. Fill in the
blanks to complete the class definition.
#include <iostream>
----------------------------Rectangle
{
--------------:
double Width;
double Height;
19
public:
//write a constructor that calls set_height and set_width functions to initialize
data members
//write a function set_height that sets the Height if it is positive, otherwise
Height will be zero.
//Function set_width that sets the Width if it is positive, otherwise Width will
be zero.
//write the header of a function area that returns the area of a rectangle
----------------------------------------------------{
return Width * Height;
}
void print()
{
//complete function print to print the data members
}
};
void main()
{
//create an object T1 from class Rectangle of width 4 and height 5
//call function area
//call function print
}
20
Class Calculator
Background:
Pre-labs:
An elementary back ground about the simple math operations (+,-,*,/)
Lab
Studey the following class definition then:
class SimpleCalculator
{
public:
// write definition for add method
21
};
int main()
{
double x=10.0;
double y= 2.5;
22
To do:
1. Modify your class so that SimpleCalculator has a private data members called
answer. After performing an operation, assign the result to answer .
2. Add a member function named getAnswer to retrieve the result of the last
arithmatic operation performed by the object.
3. Also, add a constructor for class SimpleCalculator that
initializes the value of answer to 0.
To do:
1. Modify the program so that the SimpleCalculator class has input member function
that allows the user to input two doubles. The function should then store the values
that were input in private data members a and b.
2. Create two constructors for this class, one that takes no arguments and initializes a
and b to 0 and another that takes two doubles and initializes a and b to those
values.
3. Create a member function printValues that displays the values of a and b.
4. Finally, modify the main function by adding the following code segment:
SimpleCalculator sc;
//instantiate object
sc.input();
sc.printValues();
cout<<"Adding a and b yields"<<sc.add()<<"\n";
23
Class Triangle
Background:
Triangles are classified by the number of equal sides they have to:
scalene - all 3 sides have different lengths
isosceles - 2 sides have equal lengths
equilateral - all 3 sides are equal .
If you know the length of all 3 sides of a triangle, you can
calculate the area by using Heron's Formula (sometimes called
Hero's Formula) see the figure.
First we have to define a triangle's perimeter which is (side a +
side b + side c).
A triangle's semi-perimeter (or 's') is one half of the perimeter or
to put it another way:
Semi-perimeter = (side a + side b + side c) 2
Example: A triangle has side a = 4, side b = 5 and side c = 6. What is its area?
The perimeter = 4 + 5 + 6 = 15.
The semi-perimeter is one half of this or 7.5
Using Heron's formula,
area = square root (s (s - 4) (s - 5) (s - 6))
area = square root (7.5 (7.5 - 4) (7.5 - 5) (7.5 - 6))
area = square root (7.5 (3.5) (2.5) (1.5))
area = square root (98.4375)
area = 9.921567416...
Pre-labs:
1.
2.
3.
4.
5.
Lab:
public:
24
Step 2:. Write a program that constructs a Triangle object and calls all the members
functions.
25
Class Students
Background:
The sample mean is the average and is computed as the sum of all the observed outcomes
from the sample divided by the total number of events. We use x as the symbol for the
sample mean. In math terms,
Lab
1. Write a class implementation for a class Student with the following data members:
members
StudentName of type string.
mark1, mark2, and mark3 all of them of type double.
27
The deposit value is simply added to the account balance using the following
equation (Account_Balance=Account_Balance+Deposit_Amount).
To withdraw from an account
-
The client checks the account balance to see if it is sufficient or not. If so, the
amount is deducted from the account as follows:
Account_Balance=Account_Balance-Withdraw_Amount
-
Step1: Write implementation for class bank_Account that contains the following
members:
Data members:
1.
2.
3.
4.
Member functions:
1. Empty constructor (default constructor) to initialize all data members to their
appropriate default values.
2. Parameterized constructor to initialize all data members to the given values.
3. get_Balance Function to return the account_Balance.
28
4. deposit Function which receives the amount of money to be deposited and performs
the deposit transaction according to the equation you've learned.
5. withdraw Function which receives the amount of money to be withdrawn and checks
it against the account balance to decide whether to perform the transaction or not.
Step3: Enhance your class by adding a print member function to print all the information
about the customers.
29
Background:
Separating class interface from its implementation:
Interface of the class:
- Specifies what services the class permits users to use and how to request
those services, but not specify how the services are implemented.
- Contains the prototype of the member functions and the declaration of the
data members.
- We place class interface in header file.
Define member functions outside the class definition, in a separate source-code file:
- In source-code file for a class
o Use binary scope resolution operator (::) to tie each member
function to the class definition
o Implementation details are hidden
o Client code does not need to know the implementation
Driver files (source file)
o Program used to test software (such as classes).
o Contains a main function so it can be executed.
#include preprocessor directive
- Used to include header files
- Instructs C++ preprocessor to replace directive with a copy of the contents
of the specified file
- Quotes indicate user-defined header files
- Angle brackets indicate C++ Standard Library
Validating Data with set Functions
set functions can validate data
Known as validity checking
Keeps object in a consistent state
The data member contains a valid value
Can return values indicating that attempts were made to assign invalid
data.
string member functions
length returns the number of characters in the string.
substr returns specified substring within the string.
Pre- Lab:
The student must know how to:
- Define a class and use it to create object.
30
Learning Outcomes:
You will:
- Be able to write a full documented and separated interface C++ program
that deals with classes.
- Be able to validate data members in set functions, to ensure that data in an
object adheres to a particular format or is in proper value range.
Assessment tools:
-
Lab Exercises:
Exercise #1:
Write a full documented and separated interface C++ program that implements
class Point that contains the data members x and y of type integers and the following
member functions:
1- Parameterized constructor that initializes x and y to any given values.
2- setX function to assign new value to x between 10 and 50.
3- setY function to assign new value to y, the value must be greater than or equal
to 0.
4- getX to return the value of x.
5- print to print any point as ordered pair.
Write a main function declare object p1 with the values 12 and 30 to x and y
respectively, and test the member functions.
The solution:
To create a full documented and separated interface C++ program that implements
class Point:
1- Create new project of type Win32Console Application of any name.
2- then add a header file name e.g. point.h to write the class interface as
follows:
//file name: point.h
class Point
{
private:
int x,y;
public:
Point(int, int);
void setX(int);
void setY(int);
int getX();
void print();
};
31
3then add a source file e.g. implementation.cpp to write the implementation for
each member function as follows:
//file name: implementation.cpp
#include <iostream>
using namespace std;
#include "point.h"
Point::Point(int a, int b)
{
setX(a);
setY(b);
}
void Point::setX(int a)
{
x = (a>= 10 && a<= 50)? a : 10;
}
void Point::setY(int b)
{
if(b>= 0)
y = b;
else y = 0;
}
int Point::getX()
{
return x;
}
void Point::print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
4- then add a source file named e.g. driver.cpp to write the main function and test
class operations as follows:
//file name: driver.cpp
#include<iostream>
using namespace std;
#include "point.h"
void main()
{
Point p1(12,30);
p1.print();
p1.setX(8);
p1.setY(3);
p1.print();
32
cout<<p1.getX()<<endl;
}
Exercise #2:
Write a full documented and separated interface C++ program that implements class
Student that contains the following data members:
- name of type string.
- ID of type integer.
- grade of type double.
And the following member functions:
- default constructor to initialize name to ali, ID to 2012066034, and grade
to 65.7.
- setName to assign new value to the data member name but ensure that the
name has at most 20 characters.
- setGrade to assign new value to the grade but ensure that the grade be
greater than or equal to 60.
- Print to print the student information.
Write a main function, declare object s1 of type Student and use the s1 to test all
operations of class Student.
The solution:
To create a full documented and separated interface C++ program that implements
class Student:
1- Create new project of type Win32Console Application of any name.
2- then add a header file name e.g. student.h to write the class interface as
follows:
//file name: student.h
#include<string>
using namespace std;
class Student
{
private:
string name;
int ID;
double grade;
public:
Student();
void setName(string);
void setGrade(double);
void print();
};
3- then add a source file e.g. implementation.cpp to write the implementation
for each member function as follows:
//file name: implementation.cpp
#include <iostream>
using namespace std;
33
#include "student.h"
Student::Student()
{
setName("ali");
ID = 2012066034;
setGrade(65.7);
}
void Student::setName(string n)
{
if(n.length()<= 20)
name = n;
else
name = n.substr(0,20);
}
void Student::setGrade(double gr)
{
grade= gr >= 60 ? gr: 60;
}
void Student::print()
{
cout<<name<<" "<<ID<<" "<<grade<<endl;
}
4- then add a source file named e.g. driver.cpp to write the main function and
test class operations as follows:
//file name: driver.cpp
#include<iostream>
using namespace std;
#include "student.h"
void main()
{
Student s1;
s1.print();
s1.setName("Ahmad Mohammed");
s1.setGrade(2010902023);
s1.print();
}
Lab Assignment:
Assignment #1: Write a full documented and separated interface C++ program that
implements class Calculator that contains the data member x and y of type integer and the
following member functions
1) Add to return the result of summing x and y
2) Sub to return the result of subtracting y from x
34
Write a full documented and separated interface C++ program that implements class
Account that a bank might use to represent customers' bank accounts.
- Your class should include one data member of type double to represent the account
balance.
- Your class should provide a constructor that receives an initial balance and uses it to
initialize the data member. The constructor should validate the initial balance to
ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the
constructor should display an error message, indicating that the initial balance was
invalid.
The class should provide three member functions:
- Function credit should add an amount to the current balance.
- Member function debit should withdraw money from the account and should
ensure that the debit amount does not exceed the account's balance. If it does,
the balance should be left unchanged and the function should print a message
indicating "Debit amount exceeded account balance."
- Member function getBalance should return the current balance.
Create a program that creates two Account objects and test the member functions of
class Account.
35
Teach the student, how to use if/else selection statements, and use it to write and
execute a simple program.
Teach student the structure of the switch statement.
How to convert between if/else and switch statement.
Background:
If/else Statement:
o Condition
Expression can be either true or false
Can be formed using equality or relational operators
o if statement
If the condition is true, the body of the if statement executes
If the condition is false, the body of the else statement executes
If (
Condition
)
36
{
1
Statement(s);
}
Else
{
Statement(s);
}
Switch Statement:
o Value
Integer value or variable or expression
Char value or variable
Bool value or variable
o Case statement
If the value in the switch statement is equal to the value in one of
the case statemets, the body of the case statement executes
If the value in the switch statement doesnt match any value of the
case statements , the body of the default statement executes
Case value1 :
Statement(s);
Break;
Case value2 :
Statement(s);
Break;
Case value3 :
Statement(s);
Break;
.
.
.
Default :
Statement(s);
Break;
}
38
Pre-lab:
If (
Condition
Statement(s);
39
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
Lab Assignments:
Lab assignment-1
Write a program to read character then find if it is capital or small.
#include<iostream>
using namespace std;
void main()
{
40
char letter;
cin>>letter;
if(letter >='A' && letter <='Z')
cout<<"Capital Case"<<endl;
else if(letter >='a' && letter <='z')
cout<<"Small Case"<<endl;
else
cout<<"Incorrect Caharcter..."<<endl;
}
Lab assignment-2
Implement the calculator using if/else statement. The program should ask the user to
input two operands and an operation, your program should print the result of
performing the required operation on the input operands as the following output
suggests:
Enter operand 1: 5
Enter operand 2: 10
Enter operation: /
The result of 5/10 is 0.5
#include<iostream>
using namespace std;
void main()
{
int a;
cout<<"Enter operand 1: ";
cin>>a;
int b;
cout<<"Enter operand 2: ";
cin>>b;
char op;
cout<<"Enter operation:";
cin>>op;
41
if(op== '+')
cout<<"The result of "<<a<<op<<b<<"
"<<a+b<<endl;
else if(op == '-')
cout<<"The result of "<<a<<op<<b<<"
b<<endl;
else if(op == '*')
cout<<"The result of "<<a<<op<<b<<"
"<<a*b<<endl;
else if(op == '/')
cout<<"The result of "<<a<<op<<b<<"
"<<static_cast<float>(a)/b<<endl;
else
cout<<"Incorrect operation was
entered..."<<endl;
is
is "<<a-
is
is
Lab assignment-2
Implement the calculator using switch statement. The program should ask the user to
input two operands and an operation, your program should print the result of
performing the required operation on the input operands as the following output
suggests:
Enter operand 1: 5
Enter operand 2: 10
Enter operation: /
The result of 5/10 is 0.5
#include<iostream>
void main()
{
42
int a;
cout<<"Enter operand 1: ";
cin>>a;
int b;
cout<<"Enter operand 2: ";
cin>>b;
char op;
cout<<"Enter operation:";
cin>>op;
switch(op)
{
case '+':
cout<<"The result of "<<a<<op<<b<<" is "<<a+b<<endl;
case '-':
cout<<"The result of "<<a<<op<<b<<" is "<<a-b<<endl;
case '*':
cout<<"The result of "<<a<<op<<b<<" is "<<a*b<<endl;
case '/':
cout<<"The result of "<<a<<op<<b<<" is
"<<static_cast<float>(a)/b<<endl;
default:
cout<<"Incorrect operation was entered..."<<endl;
43
Lab Problems:
Lab Problem-1:
Write a program to read four integer numbers then find and print the second maximum
one among these numbers.
Lab Problem -2
The following program has a nested if structure, however some of its cout statements
are missing reporting words in the blanks (). Fill the missing blanks with what you
think logically sound as in the bold cout, and then run the program to check its output.
#include<iostream>
using namespace std;
void main()
{
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2!=0)
if(num>10)
if(num<20)
cout<<"your numbers is ODD, >10 and
<20\n";
else
cout<<"your number is ..... and ....";
else
cout<<"your number is .... and ...";
44
else if(num<0)
cout<<"your number is ... and ...";
else
cout<<"your is .... and ....";
Lab Problem -3
Write a program that reads three nonzero integers and determines and prints whether
theyre the sides of a right triangle.
45
explain the basics of while and for loops and while loops
apply the syntaxes of loop structures
design programs using loop structures
solve (hard) problems of repetitive nature using loop structures
Background:
Loop structures called for loops and while loops are covered as some basic control
structures. The loop can be used to do repetitive calculations. Though human beings
can do calculation or processing or repetitive nature by hand, it is much slower and
tedious for the human being. Good and solid logic of loop structures can be used to
solve such problems in a very efficient way.
For example, in order to compute the sum of 1 + 2 + 3 + + 100, we can do easily
using the following code:
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
There are two control structures used often: the for loop and the while loop (and do
while as a different way of while).
The syntaxes of these two loop structures are as follows:
for (initialize loop variables; loop terminator;
loop variable update)
{
Statements in the block or one statement
}
Not all three components of the for loop are necessary, in fact for ( ; ; ) is a valid
statement. The loop variable update can be increments of loop variable(s) or
decrements; there can be more than one loop variable in the same for loop separated
by comma (,) and there can also be nested for loops of for loop inside for loop etc.
When there is only one statement in the block, the enclosing braces{} can be omitted.
The following are a few valid for loop statements
The loop structure can be used to do the following problems encountered often in the
first programming course (usually considered challenging for the students new to
programming):
46
1. Reverse an integer
2. Compute the prime number
3. Compute a function such as exp (x) (exponential function).
Pre-labs:
1.
2.
3.
4.
5.
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
Lab Assignments:
Lab assignment-1:
Reverse an integer:
Problem statement: Given an integer n such as 1367. Write a program that computes
the inverse of this integer as 7631.
#include<iostream>
using namespace std;
void main()
{
int x;
cin>>x;
while (x != 0)
{
int r = x % 10; // Get the last digit of x
x = x / 10; // divide x by 10 through integer
47
Lab assignment-2:
Compute prime number
A prime number p > 1 is a positive integer which has 1 and itself as the only factors.
Prime numbers have special properties that are different from non -prime (also called
composite) numbers > 1. For example 4 is dividing by 2 so 4 is not a prime number.
The lists of prime numbers from 2 to 30 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. To
determine if an integer n > 1 is a prime number, theoretically we need to verify that
for i = 2, 3, 4, 5, .., up to n-1, none of them divides n.
#include<iostream>
using namespace std;
void main()
{
int x;
cin>>x;
bool isPrime=true;
int i=2;
while(i<x-1)
{
if(x%i==0)
{
isPrime=false;
break;
}
i++;
}
if(isPrime)
cout<<"number is prime"<<endl;
else
cout<<"number is not prime"<<endl;
}
Lab assignment-3:
Compute power:
To calculate X y (x to the power y) where both x, y are integers we must repeat multiply x by
it self y times. For example, if x=3, y=4 so you must compute 3*3*3*3.
48
#include<iostream>
using namespace std;
void main()
{
int x,y;//x is base , y is power
cin>>x>>y;
int result=1;
for(int i=1;i<=y;i++)
result*=x;
cout<<x<<" to the power
"<<y<<"="<<result<<endl;
}
Lab Problems:
Lab Problem-1
Write a C++ program to find the summation of the following series (using for statement)
S=1+ 4 + 9+ 16++(n*n).
Lab Problem-2
Write a C++ program to print all numbers (that are multiple of 3) from 1 to 100 every 6
numbers on a line.
Lab Problem-3
Write a C++ program to find the summation of even digits for any read number from the
keyboard (the number could be of any length).
49
Lab Objectives:
After completing this lab, the students should be able to
Explain the concepts of functions.
use common math functions available in the C++ Standard Library.
Explain what a function prototype is and how that is different from the
function definition.
Convert the code processing in the main function to a function called
from the main function.
Create functions with multiple parameters.
The mechanisms for passing information between functions and
returning results.
Background:
The function is a good mechanism to encapsulate code used repeatedly in a
program so that it can be called from other parts of the code. A function does not use
a keyword called function but instead the programmer has to define function
prototype before the main function and then define the function again later.
A function has the following format:
type function_name (optional parameter list)
{
function code;
return value;
}
Return data type of function is in general the types of C++ variable types including
int, double, char etc.
The function does some processing and the calculated value is returned using the
return value.
In the main function or the other functions calling this function_name, the value
returned is used like the instruction:
calling_value = function_name (parameters);
A function does not need to always return a value. A function not returning a value
can omit the return statement and the function type is void in this case.
Function prototype has the following format:
type function_name (list of variable types);
Examples are:
Example 1:
int compute_sum (int);
50
Example 2:
void tryout ();
Function prototypes differ from the function definitions in two places: there is no
code (no {} with code in between) and the variable names do not follow the types.
A function prototype can return nothing, in which case void is the type returned; also
it may have no parameters at all like example 2 above.
The function prototype is declared before the main function with the function calls
inside the main function or the other functions calling this function.
The function definitions are put after the main function.
C++ Standard Library : is a collection of functions, which are written in the core
language and part of the C++ ISO Standard itself to provides several generic functions
that utilize and manipulate these containers, function objects, generic strings and
streams (including interactive and file I/O), support for some language features, and
everyday functions for tasks such as finding the square root of a number. Using sqrt
in <cmath> header file.
Example 3:
Pre-labs:
In order to do this lab, you should know how to write, compile, and run a C++ program, and
you should understand what functions are and how to invoke them. You should also be
familiar with an editor
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
51
Lab Assignments:
Lab assignment-1
Consider the following code that computes the sum of 1 + 2 + 3 + .. + 100 by a for
loop.
#include <iostream>
using namespace std;
int main ( ) {
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
cout << The sum of 1 + 2 + 3 + .. + 100 is << sum <<
endl;
return 0;
}
This program shows how to compute a sum in a quick way. The program can be
easily modified to compute and display the sum of 1 + 2 + .. + n for a variable n (with
n = 100 as above).
Such code of (3 lines) computing the sum can be coded as one instruction in the main
function compute_sum (n) with the variable n as the parameter.
The function prototype is declared before the main function with the function calls
inside the main function or the other functions calling this function. The function
definitions are put after the main functionas follow:
int compute_sum (int x)
{
int sum = 0;
for (int j = 1; j <= x; j++)
sum += j;
return x;
}
52
Lab assignment-2:
Write a program to read three integers in the main and then send them to the function Max
which will return the maximum number of the them .
Lab assignment-3:
Write a recursive function that receives an integer consisting of any number of digits.
Your function should calculate and return the summation of the integer digits.
Lab Problems:
Lab Problem-1
Write a function called Sum_even which takes as input two integers N and M entered by the
user from keyboard , and returns to the main function the summation of even numbers from
N to M. (note: N and M included if were even numbers) .
53
Lab Problem-2
Write a function called Is_Capital that has one parameter and receives a character and
returns true if the character received is a capital letter, and false otherwise. Then write a
main function that calls the Is_Capital function to test its correctness.(you may solve it
without using if-else statement).
Lab Problem-3
Write a C++ function to receive an integer of 3 digits then calculates and returns the sum of
the MSD and the LSD. For example if your function received 345 it should return 8.
54
Background:
If we want a random number in the range [a, b] we can use the formula
a + rand() % (b a + 1)
If the cylinder has a radius r and length (height) h, then its volume is
given by
V = r2h
, = 3.14
Pre-lab:
The student must know how to
Assessment tools:
Quizzes
Lab Assignments:
55
Lab assignment-1
Write a void function with empty parameter list to print out 100
random numbers in the range 7 to 51 every 10 in a line. Then call
it from the main function.
#include <iostream>
#include <cstdlib>
using namespace std;
void printRandomly()
{
for(int i = 1; i<=100; i++)
{
cout<<7 + rand() % (51 -7 +1)<<"\t";
if( i % 10 == 0)
cout<<endl;
}
}
void main()
{
printRandomly();
}
Lab assignment-2
Study the following code, discuss the scope rules and try it to see
and understand the results.
void main()
56
// First Block
int var1 = 5;
int var2 = 8;
int var3 = 4;
{
// Second Block
int var1 = 6;
int var2 = 9;
{
// Third Block
int var1 = 7;
cout << "variable1 = " << var1 << "\n";
cout << " variable2 = " << var2 << "\n";
cout << " variable3 = " << var3 << "\n";
}
cout << " variable1 = " << var1 << "\n";
cout << " variable2 = " << var2 << "\n";
cout << " variable3 = " << var3 << "\n";
}
}
Lab assignment-3
57
Lab Problems:
Lab Problem-1
Modify the implementation of the function in Lab assignment-1
to make it work for any given range (sent from the main).
Lab Problem -2
Write a c++ program with the following specification
1. A global int variable num without a value
2. A function F1 that prints the value of global num and
then assigns the value 5 to it.
3. A function F2 that has a float parameter called num, the
function will return the square root of the variable num
to the main when call it.
58
Lab Problem -3
Write a C++ function with default values, 1 for the radius of the
base for a cylinder and 2 for height to calculate and return the
volume of a cylinder, and then call your function from the main
with and without arguments.
Hint: If the cylinder has a radius r and length (height) h, then its volume is given by
V = r2h
, = 3.14
59
Should be able to convert any program written using loops into a recursive
one
Background:
Function signature is both the name and parameter list of that function
To overload a function is to write at least two functions at the same
scope(workspace)with different signatures[i.e. the same name but with
different parameter list (make the parameters in every list differ in types
,number, or appearance) ]
A recursive function is a function that calls itself.
Pre-lab:
The student must know how to
Assessment tools:
60
Quizzes
Lab Assignments:
Lab assignment-1
Write an overloaded function to calculate and return the area of a
square, a circle ,a rectangle. Then call it from the main function.
#include <iostream>
using namespace std;
double area(int r)
{ return r*r*3.14;}
double area(float s)
{
return s*s;
}
double area(int l,int w)
{
return l*w;
}
void main()
{
cout<<area(3);
cout<<area(3,4);
cout<<area(3.0);
}
Lab assignment-2
Write a recursive function to calculate and return the factorial of any positive integer
number.
int factorial(int r)
{
if (r<=1)
return 1;
61
void main()
{
cout<<factorial(5);
Lab assignment-3
Write a recursive C++ function to calculate and return the sum of
the following series then call your function from the main .
Sum=1+2+3+.+N
#include <iostream>
using namespace std;
int Sum(int n)
{
if (n==1)
retrun 1;
else
return n+Sum(n-1);}
void main()
{ cout<<Sum(5);}
Lab assignment-4
#include <iostream>
using namespace std;
double Volume(double );
double Volume(double, double, double );
void main()
62
{
cout<<Volume(5)<<endl;
cout<<Volume(5,5,7)<<endl;
}
double Volume(double L )
{// the volume of a Cube
return L*L*L;
}
double Volume(double L , double w, double h)
{// the volume of a Box
return L*w*h;
}
Lab assignment-5
Write a recursive function to calculate and return the power of any2 positive integer
numbers.
int power(int base,int pwr)
{
if (pwr==0)
return 1;
else return power (base,pwr-1)*base;}
void main()
{
cout<<power(2,5);
63
Lab Problems:
Lab Problem-1
Modify the implementation of the program in Lab assignment-4
to make it calculate the volume of a sphere given its integer radius
(sent from the main).
Lab Problem -2
Write a recursive C++ function to calculate and return:
Sum=1!+2!+3!++n!
Lab Problem -4
Write a C++recursive function to calculate.
X*Y (the multiplication of X by Y where X,Y are integers)
64
Lab 10 Arrays
Lab Objectives:
Learn how to use the array data structure to represent a set of related data
items.
Learn how to declare arrays, initialize arrays and refer to the individual
elements of arrays.
Learn how to pass arrays to functions.
Learn how to declare and manipulate Two-dimensional arrays.
Background:
Definition
Array: A collection of individual values, all of the same data type, stored in
adjacent memory locations.
One Dimensional Array: An array with a single variable index.
Using the array name together with an integral valued index in square
brackets refers to the individual values. The first array element always has
the subscript 0. The second array element has the subscript 1, etc.
The base address of an array is its beginning address in memory.
Declaring an Array:
Assessment tools:
Lab exercises.
Quizzes.
66
Lab Assignments:
Lab assignment-1: Fill in the blanks
Complete the following program below by filling in the blanks. (Read
comments for assistance. )
// bubble.cpp
#include <iostream>
using namespace std;
void bubbleSort(int array[], int size);
// bubble sort
void swap(int &x, int &y);
// helper function of bubbleSort
void printArray(int array[], int size); // print array
int main()
{
const int MAX = 10;
/* Declare an array called value of size MAX with
elements: 20, 15, 18, 19, 22, 11, 9, 7, 10, 3*/
cout << "Print array before sort: " << endl;
// Place print array function call here.
// Place bubble sort function call here.
cout << "Print array after sort: " << endl;
// Place print array function call here.
return 0;
}
void bubbleSort(int array[], int size)
{
for (int pass = 1; pass <= size - 1; pass++)
for (int i = 0; i <= size - 2 ; i++)
if (array[i] > array[i + 1])
swap(array[i], array[i + 1]);
}
void swap (int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
void printArray(const int array[], int size)
{
for (int i = 0; i <= size - 1; i++)
cout << array[i] << endl;
cout << endl;}
67
<<
Lab Problems:
Lab Problem-1: using array to CountDigit
Write a function CountDigit which receives two arguments: a char array and
the size of the array (of type int). This function counts the number of digit
letters in the char array, and returns the count (of type int).
68
69
Lab Objectives:
In this lab students will learn:
1. Memory concept of variables, pointers and how to use variable identifiers and
pointers to refer to the variable.
2. Pointer variable declarations and initialization.
3. Direct and indirect referencing a variable using the pointer operators.
4. Using * and address (&) operators.
Background:
When declaring a variable, it is located at a specific location in memory, the memory
address. The task of locating variables is automatically performed by the operating
system during runtime. In some cases we need to know the address where the variable
is being stored during runtime.
Variable which stores a reference to another variable is called a pointer. We can
directly access the value stored in the variable using a pointer which points to it.
Ptr
Address
Memory Locations
Syntax:
1. Pointer Declaration:
Syntax: Pointer_type *Pointer_name;
Example: int *Ptr1; double *Ptr2;
2. Pointer initialization:
Syntax: Pointer_name=NULL;
Pointer_name=&variable_name;
Example: int *Ptr1, var;
Ptr1=&var;
Assessment tools:
70
Lab Assignments:
Lab assignment-1:
Write a c++ program that defines an integer variable var1 and a pointer Ptr that
points to var1. Assign and print value to var1, then assign and print a new value to
var1 using Ptr.
Solution:
#include<iostream>
using namespace std;
void main()
{
int var1,*ptr;
ptr=&var1;
var1=10;
cout<<var1;
cout<<endl;
*ptr=20;
cout<<*ptr;
}
Solution:
Lab Problems:
Lab Problem-1: Correct the errors in the following program.
#include<iostream>
using namespace std;
void main()
{ int n,*ptr=&n;
cin>>n>>ptr;
*ptr=n-2;
if (*ptr>=0) *n++;
else
cout<<*ptr <<" IS NEGATIVE\n";
if (&n==ptr)
cout<<"CORRECT POINTER";
else
ptr=&n;
}
Lab Problem -2: Write a c++ program that use pointers to swap two
integer values.
72
Teach the students the File I/O class fstream in C++ which is used for File Read/Write
operations
Teach the students how to use file operations, use it to write and execute a simple
program.
Teach the students how to create a file using simple program.
Teach the students how to write in a file using simple program
Teach the students how to read from a file using simple program
Teach the students how to implement all previous application using file stream
Background:
Pre-lab:
Study / review how to use c++ statement in order to implement it by file process in C++.
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, he will get the participation mark for this lab.
Lab Assignments:
Lab assignment-1
Create an empty text file using c++ program and set its location
#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
file_op.close() ;
return 0;
}
Lab assignment-2
Assign value to an empty text file using c++ program
#include<fstream.h>
int main()
73
{
ofstream file_op("c:\\test_file.txt",ios::in);
int x=5;
file_op <<x;
file_op.close;()
return 0;
}
Lab assignment-3
Read value from empty text file using c++ program
#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
int x;
file_op >>x;
cout<<x;
file_op.close;()
return 0;
}
Lab Problems:
Lab Problem-1:
Write a program to find the maximum digit throw any integer number and print the
value in text file
Lab Problem -2
Write a program to read four integer numbers from file, then find and print the second
maximum one among these numbers.
74