0% found this document useful (0 votes)
63 views61 pages

CS221 - Lecture 1 C++ - Basics-1

The document provides an overview of C++ programming, covering its basics, control structures, functions, and object-oriented programming concepts. It outlines the stages of creating and running a C++ program, including the role of text editors, compilers, linkers, and loaders. Additionally, it discusses data types, variables, constants, and operators used in C++.

Uploaded by

isahisiaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views61 pages

CS221 - Lecture 1 C++ - Basics-1

The document provides an overview of C++ programming, covering its basics, control structures, functions, and object-oriented programming concepts. It outlines the stages of creating and running a C++ program, including the role of text editors, compilers, linkers, and loaders. Additionally, it discusses data types, variables, constants, and operators used in C++.

Uploaded by

isahisiaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS 221

Computer Programming II
(Lecture Note 1: C++ Basics, Control Structures & Functions)
By
Isma’il Aliyu
Department of Computer Science
Abubakar Tafawa Balewa University, Bauchi
Course Content
• C++ basics; Data types, constants, variables, arithmetic operators,
expressions, statements, input and output, pre-processor directives,
structure of C++ program.
• Relational and logical operators, the implementation of true/false
decisions.
• Iteration: for loop, while loop, do-while loop. Use of break and continue
statements. Selection: if statement, switch statements.
• Pointers and use of the * operator, appreciation of the use of pointers.
System library functions and header files, user-defined functions,
parameter passing between functions using “by value and by reference”
methods.
• Complex data types; Arrays, Structures and Unions, single and multi-
dimesional array, passing between functions, arrays of characters (string).
External file handling. Object Oriented Programming in C++; classes,
object, inheritance, and polymorphism.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 2


Reference Materials
• C++ By Dissection. Ira Pohl. Addison Wesley
Publishers 2002.
• Object Oriented Programming in C++. Robert
Lafore. 4th edition. Sam Publishers, 2002.
• C++ Primer Plus. Stephen Prata. 5th edition. Sams
Publishers, 2005.
• Chapter 7. Bjarne Stroustrup(2013). The C++
programming Language, 4th edition. Addison-
Wesley.
• www.cplusplus.co/doc/tutorial/

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 3


Computer Programming ???
• Computer programs are set of instructions written using a
PL that instruct machines (computer) to carry out specific
task.
• Programs are essentially the implementation of algorithms.
– An algorithm is a computational procedure for solving a
problem or accomplishing a desired task.
• The process of transforming algorithm into an executable
program is called programming.
• Therefore, programming is the art of communicating
algorithms to computers.
– A particular programming language must be used for
implementing the algorithm.
• Person that writes computer program is called programmer.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 4


Computer Programming ???
• In software process models (software development
methodology) such as; waterfall, V-model, spriral, and Agile
models, programming is also called coding.
• Coding is step in software development that involves
transforming the detailed description of the task
(requirements) using the syntax of programming language
into a workable program that satisfies user’s needs.
• Depending on the complexity of the software being
developed, one or more programmers required to get job
done.
• Coding (programming) is a highly technical and skilful task.
• Programmer code and test programs during software
development.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 5


The language C++
• The C++ programming language was introduced by
Bjarne Stroustrup of the AT&T laboratories in 1985.
• It is as an extension of C, with additional features.
• Since then, C++ has grown rapidly in response to the
practical need for a programming language that is able
to efficiently handle composite and diverse data types.
• The language implementation is pivoted on the
concept of object oriented programming (OOP).
• Today, C++ dominates the commercial market and is
favored among system programmers and application
developers.
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 6
The language C++
• C++ is a powerful and flexible general purpose PL with a
bias toward system programming.
• C++ is based on C but with some enhancements.
• Notable enhancement is the object-orientation capability.
• C++ is a multi-paradigm language. It supports:
• Procedural (Imperative) paradigm, and
• Object Oriented paradigm
• C++ is case sensitive.
• Lower case characters are different from upper case. Example,
“aGe” is different from “age”.
• A file containing C++ code can be saved with the following
extensions:
• .cpp, .cxx, .c++, .h, .cc, .cp

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 7


The language C++
• C++ is a compiled language. Its compilers are available for
different platforms.
• I used Dev C++ to prepare this slides.
• You can also use compilers like CodeBlock, Borland C++ etc.
• The executable file generated by compiler is not portable.
• Executable file generated on a Mac PC can’t work on a Windows
PC.
• However the source code of C++ is portable.
• C++ is a strongly typed language
• the type of every entity (e.g., object, variables, functions etc)
must be explicitly stated prior to compilation.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 8


The language C++
• Like C, C++ is a compiled language.
• For C++ program to run, its source text has to be processed by a
compiler, producing object files, which are combined by a linker
yielding an executable program.
• A C++ program typically consists of many source code files (usually
simply called source files).

• An executable program is created for a specific hardware/system


combination; it is not portable, say, from a Mac to a Windows PC.
• When we talk about portability of C++ programs, we usually mean
portability of source code; that is, the source code can be
successfully compiled and run on a variety of systems.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 9


Stages of creating & running C++
program
• These stages are the same for other compile
languages

• .

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 10


Stages of creating & running C++
program
• Stage 1: Text Editor. Text editors are used to create source
file. i.e, the statements that make up the program are
written in a text editor and saved with .cpp extension.
• Stage 2: Compiler. The compiler translates the source code
into machine readable format called object code.
– The compiler translates the entire source code at once.
– The compiler checks for syntax to make sure that the
instructions are written according to syntax of the PL. The syntax
rules are similar to grammatical rules in English. When these
rules are violated, syntax error occurs.
– For example, missing semi colon leads to syntax error. If the
program is syntactically correct, the compiler creates the object
file. The object file is the machine executable format of the
program.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 11


Stages of creating & running C++
program
• Stage 3: Linker. The linker combines all the object files
needed by the program and then create complete
object file that the machine executes.
– The files that the linker combines together are other
source files and library files that are included in the
program.
– Thus the linker links your program with the header files
you specified using pre-processor directive, and create a
complete executable file for computer to execute.
• Stage 4: Loader. The loader places the complete
executable file (machine executable format of the
program) into memory for execution
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 12
Structure of C++ program
• C++ program has the • .
following structure

#include <iostream
using namespace std;
int main() {
cout <<“Hello world! \n”;
cout <<“This is CS221 class ”<< endl;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 13


Structure of C++ program
• Every C++ program must have exactly one global
function called main which does not accept any
argument.
• The main function provides entry into the program. That is,
executions begins or starts from the main function.
• Essentially all executable statements are placed in
functions and are called directly or indirectly from the
main() function.
• C++ programs are composed of one or more functions.
• The output of the above program is simply two lines of
texts.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 14


Structure of C++ program
• The line #include <iostream> is a preprocessor directive, which
instructs the compiler to include the iostream header file.
– Standard I/O facilities or functions (such as cout, cin, etc) are found in
iostream.
– If your program involves calculations, you may wish to include maths
header file.
• The operator << (‘‘put to’’) writes its second argument onto its first
. It writes the string literal , "Hello, World!\n“ onto the standard
output stream, cout.
– A string literal is a sequence of characters surrounded by double
quotes.
• In the string literal, the backslash character \ is followed by another
character n. \n is a command for new line. That is, the cursor
should be on next line after writing Hello, World! On the screen.
• The keyword endl can be used instead of \n

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 15


Structure of C++ program
• The endl places the cursor on a new line. It also flushes the output
buffer, printing everything to that point.
• We used the statement
using namespace std;
• The essence is to inform the compiler that we wish to use objects from
the standard library.
• Without ‘using namespace std;’ statement like:
cout <<“Hello \n”;
Must be re-written as
std::cout<<“Hello \n”;
• Note that in the program, the return type of the main function is int
and we haven't explicitly return any value. Why???
• Ans: By default 0 is returned.
• However, this does not apply to other functions. You need to
explicitly return a value.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 16


Preprocessor Directive
• The preprocessor directives are commands that give
instruction to the C++ compiler to include a library to be
used in the program.
• Preprocessor statements are handled by the compiler
before the program is actually compiled.
• The #include directive gives a program access to a
library and causes the compiler to insert definitions from a
standard header file into a program before compilation.
• Note that preprocessor statements begin with a # symbol,
and are NOT terminated by a semicolon.
• Traditionally, preprocessor statements are listed at the top
of the source file.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 17


Comments
• Comments are non-executable statements that
provide description about statements, functions
and other constructs within the program.
• Comments are ignore by compiler.
• Comments allow programmer to embed
explanation on some sections of the program
• The following comments are supported in C++
• // - single line comment
• /* */ - block comment
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 18
Data types
• Data type indicate the type value a variable holds. It represent the
category or form of data.
• Like C, C++ is a static typed language.
– Data type of variables must be explicitly stated.
• By forcing the programmer to explicitly define a type for all
variables and interfaces, the type system enables the compiler to
catch type-mismatch errors, thereby preventing a significant source
of bugs.
• The list of data types supported in C++ are given in table in the next
slide
• To get the exact size of type, use sizeof() function.
– Eg, sizeof(int), sizeof(char)
• The size of a type depends on machine architecture (i.e., it varies
among different machines).

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 19


Data types
Data types Size Range
char 1 byte ASCII Characters or Short integer values. Signed:-128 to
127, unsigned: 0 to 255
short int 2 byte Signed:-32768 to +32767. Unsigned: 0 to 65535
int 4 bytes Signed:-2147483648 to +2147483647. Unsigned: 0 to
4294967295
long int 8 bytes
bool 1 byte Boolean. It has only 2 values TRUE & FALSE
float 4 bytes Single precision floating pointy numbers
double 8 bytes Double precision floating point numbers
long double 8 bytes
wchat_t Wide character used for non English letters

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 20


Variable
• A variable is memory cell that is used for storing data. The
data or value stored in a variable may be changed or
modified as the program executes.
• The name of a variable can be composed of letters, digits,
and the underscore character. The naming must adhere to
rules of naming identifier.
• Syntax of variable declaration:
• datatype variableName;
• datatype variableName = value;
• Variables of the same datatype can be declared at once but
separated by commas. Examples:
• unsigned int age = 19, count = 0, x ;
• float height = 3.25, pay = 2350.78;

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 21


Constant
• Constant is an identifier whose value remains fixed (unchanged)
throughout execution of a program.
• Constants can be of any of the basic data types
• There are two ways of declaring constants in C++
• Syntax
– Method 1: symbolic constant
• #define constantName value
– Eg:
• #define LENGTH 30
– Method 2: Using const keyword
• const datatype constantName = value;
– Eg
• const float height = 3.124;
• Note that preprocessor statements begin with a # symbol, and are
NOT terminated by a semicolon.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 22


Operators
• C++ allows operators, punctuators, and white
space to separate language elements.
• Operators are used in expressions and are
meaningful when given appropriate arguments.
• C++ has many operators. Certain symbols stand
for different operators, depending on context; for
instance, - can be either unary or binary minus.
– A unary operator is an operator on one argument, and
– a binary operator is an operator on two arguments.
• C++ operators used in expression are illustrated in
the table in the next slide
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 23
Operators
Operator Meaning
Arithmetic + , - , * , / , % Addition, Subtraction,
Multiplication, Division,
Modulus
Relational < , > , == , <= , >= , != Less than, Greater than,
equals, Less than or equals
to, Greater than or equals
to, Not equals to
Logical && , || Logical AND, Logical OR
Assignment =, +=, *= , -= Assign, add and then
assign, multiply and then
assign,
Increment and Decrement ++, -- Increment, Decrement

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 24


Writing Mathematical formulas
• Some times you may need to borrow
mathematical formulas to solve a program.
• Below are correct ways of encoding
mathematical formulas in C++
• b2 – 4ac = b*b – 4*a*c
• a(b+c) = a*(b+c)
1
• = 1 /(k+x*y)
𝑘+𝑥𝑦
−𝑏+ 𝑏 2 −4𝑎𝑐
• = (-b + sqrt((b*b) – 4*a*c))/(2*a)
2𝑎

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 25


I/O Statements
• If you are learning new PL, familiarity with Input and output
statements are among the first things expected of you.
• By default, the standard output device is the screen
(monitor), while the standard input device is keyboard.
• The C++ standard I/O library is iostream.
• The iostream library overloads the two bit-shift operators.
• << // "put to" output stream
• >> // "get from" input stream
• This library also declares three standard streams:
• cout // standard out
• cin // standard in
• cerr // standard error

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 26


I/O Statements
• Therefore, C++ uses the operators << and >> for output and
input respectively.
• Output Statement
– It is accomplished using the keyword cout, pronounced “see -
out”. examples
cout << “Hello, welcome to CS221 class”<<endl;
float ans = 45.6;
cout << “The answer is: ”<< ans <<\n;
• Input Statement
– It is accomplished using the keyword cin, pronounced “see - in”.
Example
int val;
cin >> val ;

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 27


Example – I/O Statement
• Write a program that let user enter 2 different
numbers, compute their sum, product and display the
results accordingly.
#include <iostream>
using namespace std;
int main() {
cout <<“please enter 2 different numbers ”<< endl;
float first_num, second_number, sum, product;
cin >> first_num;
cin >> second_num;
sum = first_num + second_num;
cout <<“The sum of the numbers is: ”<< sum<<endl;
product = first_num * second_num;
cout <<“The product of the numbers is: ”<< product<<endl;
return 0;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 28


Increment and Decrement
• Important unary operators that are frequently used in
program are the
– increment(++)
– decrement(--)
• Each of them can take any of the two forms
– Prefix – comes before the variable eg. ++a, or --a
– Postfix – comes after the variable eg. a++, or a--
• Both the increment and decrement operators changes
the current value of a variable by 1.
• The difference between the prefix and postfix is only
visible when they are used inside arithmetic expression
as shown in the following examples
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 29
Pre & Post Increment/Decrement
• Example int a = 4, b = 4, m, n;
m = 3 * a--;
#include <iostream>
n = 3 * --b;
using namespace std; cout << "a = "<<a<<", b =
int main (){ "<<b<<", m = "<<m<<", n =
"<<n<<endl;
cout << “Pre&Post Increment Demo\n”; cout <<“******”<<endl;
int c = 6, d = 5, e, f, g;
int k = 5, x, y,z; e = c--;
x = k++; f = ++d;
y = ++k; g = e * (++d) + f * (--c);
cout << "x = "<<x<<", k = "<< cout << "c = "<<c<<", d = "<<d<<
k<<", y = "<<y<<endl; ", e = "<<e<<", f = "<<f<<", g =
z = x + k++ + y * ++k; "<<g<<endl;
cout << "z = "<<z<<", k = "<<k<< return 0;
endl; }
cout <<“******”<<endl;

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 30


Control Structures
• Control structures control the flow of execution of
program.
• By default, CPU execute statements one after another
in the order in which they are written..
– This pattern of program execution is called sequential
execution.
• In the early PLs, flow of control is altered using goto
statement. However, this was eliminated and the
notion of structured programming emerged.
• Like other PLs, C++ support control structures for
selection (Decision making), and loop, i.e, repeated
execution of statements.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 31


Control Structures
• The concept of structured programming among other
requirements, dictates that programs be written in terms of three
control structures namely:
– Sequence Structures: Unless directed otherwise, in this structure
computer executes C++ statements one after the other.
– Selection Structures: allows you to make a choice of which statement
to be executed next. Like in other languages, there are two control
structures for selection in C++.
• if statement
• switch statement
– Repetition Structures: also called loop, it enables repeated execution
of certain statements provided a certain condition (called loop
condition) remains true. This structure is also in three different flavors
• while loop,
• do...... while loop
• for loop

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 32


If statement
• If statement controls CPU to make decision in
the course of executing program. That is,
select or chooses which statement(s) to
execute among others
• If statement can take 3 different forms.
– If statement with one alternative
– If statement with two statement
– Nested if statement. Ie, If statement with multiple
alternatives

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 33


If statement with one alternative
• If statement with one alternative • Cond can be joined with logical
has the following syntax: operators (&& ||). eg
– (a>=40 && a<=100)
if (cond) – (age >= 18 || vs == true)
statement • The Statement within the blocks
• or are executed when cond is
if (cond) { evaluated to true.
Statement_1 • When there are several
Statement_2 statements to be executed within
Statement_n a block, the statements must be
} enclosed with curly braces
• Example:
• Where cond is a boolean If(score >=40){
expression. cout<< “You Passed.”<<endl;
– Eg (a<40), (v != k), (b==0) cout << “Congratulations \n”;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 34


If statement with two alternatives
• Here the keyword else is • Example
added to provides avenue
for executing the second float score;
block when cond is cout << “Please enter a score”<< endl;
evaluated to false cin >> score;
• The syntax is If (score >= 40){
if (cond) cout <<“You passed”<<endl;
Statement_true cout<<“Congratulations\n”;
else }else{
Statement_false cout << “You failed”<< endl;
cout<<“Work hard next time \n”;
• Curly bracket must be used }
hen there are more than
one statements with a block

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 35


Nested if statement
• Nested If statement is used to code • The above example can be re-written
decisions with multiple alternatives. in a more clearer way using the else
• The level of nesting depends on the if keyword as follows:
task. However, sometimes nesting if
statement is confusing and difficult If(score>=0 && score <50)
to debug, and results in logic error. cout<<“You Failed\n”;
• Examples. else if (score >= 50 && score <=100)
cout<<“You passed\n”;
If (score>=0 && score<=100){ else
If(score>=50) cout<<“Invalid score”<<endl;
cout<<“You Passed.\n”;
else
cout<<“You failed \n”; • Therefore, second examples is clearer
}else{ and less confusing,.
cout<<“Invalid score”<<endl; • Thus, if statement with else if can
take care of what ever level of
} nesting.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 36


Example – Nested if statement
//Program that prompt user to enter cgpa and determine the degree class.
#include <iostream>
Using namespace std;
int main (){
float cgpa;
cout << “Please enter your cgpa, a number in the range 0-5”<< endl;
cin >> cgpa;
If (cgpa >= 4.5 && cgpa<=5)
cout <<“Your degree class is first class”<<endl;
else if (cgpa >= 3.5 && cgpa<4.5)
cout <<“Your degree class is second class upper”<<endl;
else if (cgpa >= 2.4 && cgpa<3.5)
cout <<“Your degree class is second class lower”<<endl;
else if (cgpa >= 1.5 && cgpa<2.4)
cout <<“Your degree class is third class”<<endl;
else if (cgpa >= 0 && cgpa<1.5)
cout <<“Your degree class is pass”<<endl;
else
cout << “Wrong input”<< endl;
return 0;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 37


Switch Statement
• Like nested if statement, Switch statement is
aselection control structure that selects among many
different actions or group of actions.
• It is therefore, referred to as multiple selection
statement.
• Unlike If statement,
– the expression controlling switch statements is not
boolean.
– The choice of a particular block (alternative) is based on a
variable or expression that computes to an integral value
(Integer or character)
– Break statement must be the last statement of any block to
exit the switch

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 38


Switch statement
• The syntax of switch statement • Where expr is an legal
is as follows: expression that can be
evaluated to Integer number
switch (expr) { or character literals.
case value_1: • When expr matches value_n,
Statement_1; statement n is executed.
break; • When expr did not match any
case value_n: of the cases, default-
Statement_n; statement is executed.
break;
default:
• Break statement must the last
Default-Statement;
statement of any block.
break; • Note that expr is not a
} boolean expression, so logical
operator can’t be used

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 39


Switch statement – example

unsigned short int number; case 3:


cout << "Enter a number between 1 and 5: \n“; cout << "Excellent!\n";
cin >> number; break
switch (number) { case 2:
case 0: cout << "Masterful!\n";
cout << "Too small, sorry!\n"; Break;
break; case 1:
case 5: cout << "Incredible!\n";
cout << "Good job!\n"; break;
Break; default:
case 4: cout << "Too large!\n";
cout << "Nice Pick!\n"; break;
Break; }

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 40


Switch statement – example
• In the above example (previous slide), a user is
prompted to enter a value between 1 and 5.
• Any entry made by user has corresponding
match.
– When user enter 1, the output that will be displayed
on the screen is “Incredible!”
– When 5 is entered, “Good job!” will be displayed.
– When the value entered did not match any of the
cases, i.e, 0, 1,2,3,4, and 5, the out will be “Too
large!”

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 41


Loop (Repetition or Iterative)
• Many computational problems are solved by repetitive
execution of some statements.
• There are two ways to do that,
– Recursion – a function calling itself
– Iteration – do the same thing again and again.
• For eg, machine learning algorithms are train iteratively to
learn patterns by repeatedly acting on the same data set.
• Loop structures are needed to accomplish any repetitive or
iterative task.
• The following loops are supported in C++
– While loop
– Do while loop
– For loop

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 42


While loop
• The syntax of while loop is • The loop body is repeatedly
while (cond){ executed until cond is false
//Loop-body-statement • Example: print Hello world
} 10 times
• Where cond is a boolean int x = 1;
expression that control the while (x <= 10) {
execution of loop body. cout <<“Hello world \n";
– When it is evaluated to true, x ++;
the loop-body-statement is }
executed. • Note that loop variable
• At any cycle of the loop, must be explicitly altered or
cond is tested to determine updated at the end of the
whether to execute the loop loop body otherwise the
body again or not. loop will be infinite.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 43


do-while loop
• In while loop, a condition is • Where cond is boolean
tested at the beginning to expression that is tested
determine whether the after loop body execute.
loop body should execute. • Example: print Hello world
• In a do-while loop, reverse 10 times
is the case, loop body is
executed first before testing int x = 1;
or evaluating the condition {
• The syntax is: cout <<“Hello world \n";
do { x ++;
Loop body } while (x <= 10);
} while(cond);

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 44


For loop
• For loop is considered the • Where
most straight forward and easy – init is a mathematical
to use loop. expression that provides initial
– because all the loop control value of the loop variable
elements (initialization, update, – Cond is a boolean expression
etc) are gathered in one place that determine whether loop
body should execute or not
– Update is a mathematical
• The syntax of for loop is: expression that update
(increment or decrement) the
for(init; cond; update){ loop variable
// loop body • Example: print Hello world 10
} times.
for(int x =1; x<=10; x++){
Cout << “Hello world \n”;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 45


Nested for loop
• Like if statement, loop statements can be
nested. ie, one inside another.
• However, the common practice has been to
nest for loop.
• For loop must must be nested in order tgo
process two-dimensional array (martix).
• See slide 17 of note 2 for an example

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 46


Example
• Write a program that let user enter 5 • Write the program that let user enter
different numbers and compute the a number and compute its factorial.
sum of those numbers.
#include<iostream>
#include<iostream> using namespace std;
using namespace std; int main(){
int main(){ unsigned int N, factorial = 1;
float number, sum; cout<<“Please enter a number”<<endl;
for(int x =1; x<6; x++){ cin>>N;
cout << “Please enter a number\n”; for(int j = N ; j >1; j = j -1){
cin >> number; factorial = factorial * j;
sum = sum + number; }
} cout<< “The factorial of << N << “is:
Cout<< “The sum of the numbers is: <<factorial<< endl;
”<<sum<< endl; return 0;
return 0; }
}
• Ex: Re-write the above program using
while and do-while loops.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 47


Exercises
• Write a program that let user enter a single character. If
Y is entered, the program should display “Thanks for
accepting the offer”. If N is entered, display “Thanks for
declining the offer”. The program should display
“Invalid response” for any character entered apart from
the ones mentioned.
• Write a program that let user enter 10 different
numbers and compute the average of those numbers.
• Write a program that print integer numbers multiple of
8 between 200 and 500
• Write a program that displays integer numbers from 50
down to 20.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 48


Function
• A function is a subprogram that accept
parameters as input, process them and optionally
returns a value.
• It is a group of program statements organized
into a unit. This unit can be invoked from other
parts of the program.
• Functions are sometimes called methods or
subroutine in other languages.
• Typically, functions are invoked or called in the
course of program execution.
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 49
Functions
• Recall that we earlier mentioned that every C++ program has at
least one function, the main() and this is where execution begins
• Execution continue line by line until a function call is encounter
where the control is transferred to that function.
• When that function finishes, control is returned to the line
immediately after the call.
• Functions facilitate modularity in program development, by
separating tasks into self-contained units.
• The advantages of writing program with functions are;
– The task becomes easier to manage as program is broken into small
units.
– It makes debuging, testing and maintain easier.
– reuse of code.
– avoiding repeating codes.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 50


Functions
• There are two types of functions:
– Built-in functions: they are part of your compiler package
supplied by the manufacturer for you the user,
– User-define function: the one created by user himself to
serve a particular purpose.
• We have used some few library functions among many
already available in the C++ standard library in this
course so far.
• Below are additional examples of math library
functions available in <cmath> header file that enables
you to perform mathematical calculations.
– exp(x), cos(x), sin(x), pow(x,y), log(x),

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 51


User-define functions
• User define functions are the ones created by
user.
• In order to use user-define functions in C++
program, one must understand three things:
– Function prototype – declare a function
– Function definition – the body of a function
containing statements to be executed
– Function call – to execute a function

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 52


Function prototype
• Just as you can’t use a variable without first declaring
it, same applies to user-define function.
– You can’t use a function without telling the compiler about
it (declaring it).
• Function declarations are also called prototypes, since
they provide a blueprint for the function.
– They tell the compiler, “a function that looks like this is
coming up later in the program.
• Function prototype provides the following information
– Function name
– Return type – the data type of value return by the function
– Parameters – the input arguments to the function

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 53


Function prototype
• The parameters to a function are the values to be passed to the
function. the actual value passed in by the calling function is called
the argument. However, many programmers use these two terms,
parameters and arguments, as synonyms.
• The syntax of function prototype.
– return_datatype functionName (parameters);
• Suppose a function is to add two numbers, the numbers are
parameters to the function. Here's a how the function prototype
should be written.
int sum (int a, int b);
• Note that function prototype
– ends with semi colon
– did not specify the function body
– Is place at the top immediately after preprocessor directives

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 54


Function Definition
• Function definition specify the statements to be
executed when the function is invoked
• Function definition has two things
– Header – specify return data type, function name and
parameter list. Header is exactly the same with function
prototype only that it didn’t ends with semi colon. The
header must match the function prototype.
– Body – the set of statements enclosed in curly brackets
• When the keyword void is used as return type of a
function, there must not be return statement at the
end of the function. Conversely, if object any of the
data types listed previously is used as return type,
there must be return statements at the end.
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 55
Function Definition
• The syntax of function definition is:
returnDataType functionName(parameter-list)
{
function_body
}
• Example
– Below is the definition of a function that add two different numbers
int sum (int a, int b)
{
int s = a + b;
return s;
}
• Note that we return s, which is a value that matches the return type
of the function

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 56


Function Call
• A call to function causes the statements within the
function’s body to execute.
• To call a function, type the function name followed by
parameters separated by commas and enclosed in
parenthesis.
– sum(5,8);
– computeFactorial(10);
• Function call can appear before or after function definition.
• Function can be called as many times as possible in the
course of program execution.
• Now, putting together function prototype, function
definition and function call, all of them must have matching
name, return type and parameters.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 57


User-define function – example
• The following are examples of
how to create and use user- int sum(int a, int b){
define functions int s = a+b;
return s;

#include <iostream> }
using namespace std;
// function prototypes void cdSquare(int x){
int k = x*x;
void cdSquare(int x); cout << “square of ”<<x<<“is = ”<<k<< endl;
int sum(int a, int b); }

int main(){
cout << “Welcome to function demo”<< endl;
int v = sum(67, 56);
cout<< “Sum of 67 and 56 is ”<< v<<endl;
cdSquare(v);
return 0;
}

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 58


User-define function – Analysis of
example on previous slide
• In the example above, two user-define functions were
created, sum and cdSquare.
– sum function accepts two numbers of int type as parameters
and return their sum.
– cdSquare function accepts one number of int type as
parameter, compute and display the square of the number
passed.
• In the main function,
– A call is made to the sum function, where 67 and 56 were
passed and the return value is assigned to a variable v.
– A call to cdSquare function is made where the variable v, which
is the sum of 67 and 56 , is passed as parameter.
• Note that cdSquare function as no return statement at the
end because void is used as the return type of the function.

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 59


Parameter Passing
• Recall functions accepts and process data. There
are 4 methods of passing input arguments to a
function
– Pass by value – pass actual values. eg, 5, 40 etc if the
parameters are integers
– Pass by name – pass a variable name
– Pass by reference – A reference provides an alias—a
different name—for a variable. Instead of a value
being passed to the function, a reference to the
original variable, in the calling function, is passed
• We have used the first two in our previous
examples.
CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 60
Recursion
• The existence of functions makes
possible a programming technique unsigned long fact = factfunc(n);
called recursion. When used correctly cout << “Factorial of “ << n << “ is “ << fact
this technique can be surprisingly << endl;
powerful. return 0;
• Recursion means a function calling }
itself.
• The example below uses recursion to // A factfunc to calculate factorials
compute factorial of a number. unsigned long factfunc(unsigned long n){
if(n > 1)
#include <iostream> return n * factfunc(n-1); //self call
using namespace std; else
//function prototype return 1;
unsigned long factfunc(unsigned long); }
int main() {
int n; //number entered by user
cout << “Enter an integer. “<<endl;
cin >> n;

CS221_24/25_I. Aliyu. DCS,ATBU BAUCHI. 61

You might also like