0% found this document useful (0 votes)
20 views38 pages

Module 2 CSC 201

Uploaded by

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

Module 2 CSC 201

Uploaded by

peacewrld27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

MODULE 2: Variable Use, Basic Input/Output,

Control Structures

Objectives
By the end of this module, you will be able to:
 explain the purpose of C++ keywords
 understand and use datatypes
 know how to make variable declaration and
initialization
 identify valid identifiers and variable naming systems
 use and know the reasons for global and local
variables
 understand program flow and control structures
 implement basic Input /Output (I/O)
MODULE – 2: Variable Use, Basic Input/Output,
Control Structures (General Review)

 UNIT –3.1 C++ keywords


 UNIT –3.2 Data types
 UNIT –3.3 Variable names
 UNIT –3.4 Some Control Structures
UNIT 2.1 : C++ keywords

C++ keywords are the reserved words for the


language with predefined meanings. It means they
should not be used as mere variable names or
identifiers by programmers.
More so:

The C++ language contains the C language

keywords and also adding some others


Each keyword has specific syntax and actions

associated with it.


C++ keywords

Fig.3.1: C++ keywords


2.2 Data types

 A data type is a computer representation of an


Abstract Data Type (ADT); (an ADT is the
mathematical model (composition or makeup) of a
data object).
 Programming Languages usually have built-in data
types that have their own ADT( mathematical
implementation ). e.g. INTEGER ADT in C language
declared as “int” defines the set of numbers given by
the union of set (-1, -2, -3, - - - , -∞ ) and the set of
whole numbers (0, 1, 2, - - - , + ∞ ). The INTEGER ADT
also specifies the operations that can be performed on
integer numbers (e.g. addition, subtraction,
multiplication and division).
2.2 Data types

 When a design or a program requires data types


that are not in the programming language, we
must construct the necessary data types by using
built-in data types. When constructed, they are
called user-defined data types.

 In a strongly-typed language as C/C++, one must


specify the type for each data item.
 E.g. to use variable “i” as a counter in a program,
we simply introduce it to the program as follows:
int i;
Common Data Types:

Fig.3.2: primitive data types and their representations


2.3 Variable names

 A variable is the container that hold data;


could be described as an Identifier
 The data that is placed in the variable is
referred to as the variable’s value.
 The format for variable declaration is :
data_type variable_name;
e.g.: int x;
Rules for all Identifiers:

An identifier is the name of a user-defined object, a


variable, a function, class, or a label.
An identifier is made up of one or more characters. The

first character must be one of A-Z or a-z or underscore (_)


Characters following may include the digits 0-9

Uppercase and lowercase characters are distinct; i.e

CourseName is is different from courseName


Names cannot contain any symbols, such as ~ ! @ # $ %

^ & * ( ) – “+ = \ | ’, nor can they have any spaces.


Keywords cannot be used as variable names.

Identifiers may be any length, but only 1,024 characters

are significant.
Rules for all Identifiers…

 Example of some valid variable


names/Identifiers:
 unit_cost
 y
 totalCost
 Y2
 _tape
 Bottle306
Assigning Values to Variables

 C++ allows the programmer to be flexible in writing


declaration and assignment statements.
 type identifier = initial value ;
 e.g. int n = 5;
 or
 type identifier (initial_value) ;
 e.g. int a (0);
 or assigned through user’s input using an input
statement e.g. cin >> identifier;
 e.g. cin >> score;
 Other example: double money, speed; //declaration
money = speed = 0.0; //multiple assignment
C++ Does Not Initialize Variables

 C++ does not assign any values


automatically to your variables.
 The compiler warns that values are not
initialized.
 It is a good programming practice to assign
initial value to your identifiers, this could
help prevent logic errors as while the
program executes.
Scope of a variable(Local and
Global)
 A variable declared inside a function is local
to that function i.e. it is called a local
variable of that function. Only such function
can see and use it.
 A variable declared outside a function (s) is
called a global/external variable
 A variable is visible and accessible starting
from the part of the program/module where it
is declared till the end of that
program/module.
 A variable must be declared before it is used.
General Format of a C++ Program

 C++ programs are written inside functions.


 A function has a specific format, it has a name, a means
to pass data into it and obtain
 data from it.
 A function does a specific task of a program.
 C++ program execution starts from is the function
main().
 The cout (“cee-out”) object is used with the extraction
operator (<<) to send standard output to the screen.
 To obtain Program Data from the Keyboard (the user),
the cin (“cee-in”) object is used with the extraction
operator (>>).
TUTOR MARKED ASSESSMENT (TMA)

Assignments/Tasks for the students:


1. What is the problem with the following if used as a variable name: catch
2. What is the possible danger in making a supposedly local variable global
3. Which of the following are valid identifiers and why:
a) Empire01
b) Employer tag
c) @status
d) _Pension
e) -Pension
2.4 Basic Control Structures

 There are 3 basic program flow constructs, namely:


1. Sequencing
2. Selection
3. Repetition

1. SEQUENCING:
 By natural/default construct , a program proceeds

execution from one statement to the next (orderly) till


termination except interrupted/re-directed to flow in
another direction. E.g. x =10;
x = x + 2;
x = x * 2;
 It executes in the above order, from first to last till value

24 is stored in x
2.4 Basic Control Structures

2. SELECTION:
This is a program control construct/structure used to alter the
natural/ sequencing construct. One of the common statement
used to selectively execute a particular part of a program
based on the programmer’s choice is the if selection
statement.
 if(condition) statement;
• If is the keyword
• (condition) is a boolean expression which results into
true/false
• The statement that follows immediately is executed if the
condition is true else it is skipped without being executed,
then the condition is terminated.
If Statement Example:

The if selection statement


is a single-selection Yes
statement because it
selects or ignores a single Score > 79 Excellent Student
action (or a single group of
actions –block of codes).

 float score;
 cin >> score;
 If(score > 79)
 {
 Cout<< ”\nExcellent
Student”;
 }
If else statement Example:

The if…else statement is called a double-selection statement because it selects


between two different actions (or groups of actions).
Conditional Operator (?:) working as double-
decision/selection statement

 C++ provides the conditional operator (?:), which


works like the if…else statement. This conditional
operator is C++’s only ternary operator—one
that takes three operands. The first operand is a
conditional expression, the second operand the
result you get if the conditional expression is true
and the third operand is the value for a false
result from the expression. Consider the following
output:

 cout << ( grade >= 50 ? "Passed" : "Failed" );


Nested IF

 This is a multiple selection structure


 NESTED IF statement: this is when there is an IF … ELSE statement inside
an IF statement or an IF THEN statement.

false express true


ion

expr
statemen true false
essi
t1
on
statemen statemen
t2 t3
Nested if Example :
Nested IF If Age < 16 years deny scholarship
Else if sex = male grant scholarship in
African Countries
Else grant scholarship in African and
American Countries
If else if else statements : compound if

 An example is a code fragment to determine the


rank of a student grade based on its score:
 if (score > 79) Grade = “Excellent”;
 else if(score > 59) Grade = “Good”;
 else if (score > 49) Grade = “Passed”;
 else Grade = “ Repeat”;
Fig. 3.5: If else if else statements
Switch Statement

 The switch selection statement is called a multiple-


selection statement because it selects among many
different actions (or groups of actions):
 The basic form of the switch:
 switch(variable)
 {
 case value1:
 //statements 1 or function call
 break;
 case value2:
 //statements 2 or function call
 break;
 :::::::::// all case statements before default
 default:
 //statement to take care of what is not in earlier options
 } // end of switch statement
Switch Statement structure

Input
option

option true state Brea


1 ment k
false
true state
option Brea
2 ment k

true state Brea


option
n ment k
false
Default
statement
Switch Statement

 int group;
 cin >> group; // read in group type from keyboard
 Switch(group){
 case 1: cout << “This is SS1 class\n”;
 break;
 case 2: cout << “This is SS2 class\n”;
 break; //what if the break statement is
omitted here?
 case 3: cout << “This is SS3 class\n”;
 break;
 default: cout << “This is not a group\n”;
 } // end of switch statement
Switch Statement

 The statement is executed based on the particular input


passed into variable group.
 The break statement makes the compiler not to execute
the subsequent statement which is what convention
demands of program flow construct referred to as
sequencing (i.e. execute the next code after the
immediate). But what if the break statement is omitted
anywhere for example in case 2? If the value in variable
group is 2, the program jumps into case 2 according to the
switch statement construct, then executes the next
statement and so on until a break statement is
encountered.
 For such error, our output from the above code chunk is as
follows:
This is SS2 class
This is SS3 class
3. Repetition (Loop /Iteration
Constructs)

Major variation include:


 For loop

 while loop

 do…while loop

This is another way to alter the natural sequencing


process of program execution. When the program
is expected to execute a particular instruction or a
group of them in a number of times repeatedly.
These are also referred to as
loop/iterative/repetitive constructs.
for loop : general format in C++

 for(initialization; condition; increment_step) statement;


 for - is the keyword
 Initialization - sets a loop control variable to an initial value
and it is logically executed once before the first iteration of the
loop.
 Condition -The loop termination test, is executed before each
iteration of the loop begins. The number of times the
termination test is executed is one more than the number of
times the loop body is executed (e.g. if number of loop is n,
termination test goes in n+1 times). This forces the
termination to happen.
 Increment_step - the loop counter, “increment step”, is
executed once per loop iteration. It determines how the loop
control variable is changed each time the loop iterates
For statement structure

Test true
Initial modific
conditi
value ation
on

Action
false stateme
nt
for loop Implementation Example:

 for(int loop_count = 1; loop_count < 5; ++loop_count)


 cout <<“\nloop_count: " << loop_count;
 }
 This loop iterates four times and gives the following
output:
 loop_count: 1
 loop_count: 2
 loop_count: 3
 loop_count: 4 (because the loop is to terminate
before the 5th iteration)
Therefore, we can say 5 is the terminal value ( what it uses to stop).
++loop_count can be interpreted as: loop_count = loop_count + 1;
“similarly : – –loop_count means loop_count = loop_count - 1;
While loop constructs:

 There are two major construct here:


 1. while (condition){…} and
 2. do{ … }while(condition);

 1) The while(condition){…} is commonly referred to


as the while - do construct. This is called a pretest
loop. That is, test is carried out before the loop action
takes place. It means that if the test condition is not
true, then loop will not happen. That means, it is a loop
useful if you want an iteration to happen at zero or
more times. E.g. in input validation coding as follows:
while (condition){…}

expression1

HI LE
W False (ENDWHILE)
testing
condition

True (DO)
action statement output
(s) (optional
)

output
While loop constructs:

 double mark;
 mark = 10;
 while(mark > 0)
 {
 cout << “Printing as long as mark has not reached
zero\n”;
 mark- -; // decrement the value of mark by one after
each loop
 }
2. do…while structure

Action

Output

Test true
conditio
n
false
2. do{ … }while(condition);

 This is called the post-test loop. That is, the test is


carried out after the loop action. This means that the
instruction in the loop will happen at least once before the
test condition take place. It then means the loop action
happens at one or more times.
 E.g. consider the following code fragment:
 int studentCount = 1; //initial value of studentCount
 do {
 cin >> score;
 if (score>49) cout << “Pass Grade\n”;
 ++studentCount; // increment count
 }while(studentCount <=10);

Here, there is at least one student in a class for the course to exist.
END OF MODULE ASSESSMENT (EMA)

Assignments/Tasks for the students:


1. Write the output of the following code listing if the value of studentGrade is 80:
if ( studentGrade >= 60 )
cout << "Passed.\n";
else
{ Black Box
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
2. What is the minimum number of times a while(condition){…} loop can execute
3. The second conditional statement in the for() loop is to be executed in how many times
4. How many times does each of the following loop run?
a. for (j = 1; j <= 100; j++)
b. for (j = 100; j >= 1; j--)
c. for (j = 2; j < n; j++)

You might also like