0% found this document useful (0 votes)
12 views115 pages

C Revision

The document provides a comprehensive overview of C++ programming, covering its origins, terminology, variables, data types, operators, input/output, and control structures such as if statements. It emphasizes the importance of proper syntax, data assignment, and the use of libraries and namespaces. Additionally, it discusses error handling and program style, aiming to enhance readability and maintainability in C++ code.

Uploaded by

tero Ab
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)
12 views115 pages

C Revision

The document provides a comprehensive overview of C++ programming, covering its origins, terminology, variables, data types, operators, input/output, and control structures such as if statements. It emphasizes the importance of proper syntax, data assignment, and the use of libraries and namespaces. Additionally, it discusses error handling and program style, aiming to enhance readability and maintainability in C++ code.

Uploaded by

tero Ab
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
You are on page 1/ 115

HIGHER TECHNOLOGICAL INSTITUTE

(HTI)

Mechatronics Department

Digital System Design

Dr. Tarek Abbas

C++ revision
Introduction to C++
• C++ Origins
– Low-level languages
• Machine, assembly
– High-level languages
• C, C++, ADA, COBOL, FORTRAN
– Object-Oriented-Programming in C++

• C++ Terminology
– Programs and functions
– Basic Input/Output (I/O) with cin and cout
Display 1.1
A Sample C++ Program (1 of 2)
Display 1.1
A Sample C++ Program (2 of 2)
C++ Variables
• C++ Identifiers
– Keywords/reserved words vs. Identifiers
– Case-sensitivity and validity of identifiers
– Meaningful names!

• Variables
– A memory location to store data for a program
– Must declare all data before use in program
Data Types:
Display 1.2 Simple Types (1 of 2)
Data Types:
Display 1.2 Simple Types (2 of 2)
Assigning Data
• Initializing data in declaration statement
– Results "undefined" if you don’t!
• int myValue = 0;
• Assigning data during execution
– Lvalues (left-side) & Rvalues (right-side)
• Lvalues must be variables
• Rvalues can be any expression
• Example:
distance = rate * time;
Lvalue: "distance"
Rvalue: "rate * time"

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1-8


Assigning Data: Shorthand Notations

• Display, page 14
Data Assignment Rules
• Compatibility of Data Assignments
– Type mismatches
• General Rule: Cannot place value of one type into variable of
another type
– intVar = 2.99; // 2 is assigned to intVar!
• Only integer part "fits", so that’s all that goes
• Called "implicit" or "automatic type conversion"
– Literals
• 2, 5.75, "Z", "Hello World"
• Considered "constants": can’t change in program
Literal Data
• Literals
– Examples:
• 2 // Literal constant int
• 5.75 // Literal constant double
• "Z" // Literal constant char
• "Hello World" // Literal constant string

• Cannot change values during execution


• Called "literals" because you "literally typed"
them in your program!
Escape Sequences
• "Extend" character set
• Backslash, \ preceding a character
– Instructs compiler: a special "escape
character" is coming
– Following character treated as
"escape sequence char"
– Display 1.3 next slide
Display 1.3
Some Escape Sequences (1 of 2)
Display 1.3
Some Escape Sequences (2 of 2)
Constants
• Naming your constants
– Literal constants are "OK", but provide
little meaning
• e.g., seeing 24 in a pgm, tells nothing about
what it represents
• Use named constants instead
– Meaningful name to represent data
const int NUMBER_OF_STUDENTS = 24;
• Called a "declared constant" or "named constant"
• Now use it’s name wherever needed in program
• Added benefit: changes to value result in one fix
Arithmetic Operators:
Display 1.4 Named Constant (1 of 2)
• Standard Arithmetic Operators
– Precedence rules – standard rules
Arithmetic Operators:
Display 1.4 Named Constant (2 of 2)
Arithmetic Precision
• Precision of Calculations
– VERY important consideration!
• Expressions in C++ might not evaluate as
you’d "expect"!
– "Highest-order operand" determines type
of arithmetic "precision" performed
– Common pitfall!
Arithmetic Precision Examples
• Examples:
– 17 / 5 evaluates to 3 in C++!
• Both operands are integers
• Integer division is performed!
– 17.0 / 5 equals 3.4 in C++!
• Highest-order operand is "double type"
• Double "precision" division is performed!
– int intVar1 =1, intVar2=2;
intVar1 / intVar2;
• Performs integer division!
• Result: 0!
Individual Arithmetic Precision
• Calculations done "one-by-one"
– 1 / 2 / 3.0 / 4 performs 3 separate divisions.
• First 1 / 2 equals 0
• Then 0 / 3.0 equals 0.0
• Then 0.0 / 4 equals 0.0!

• So not necessarily sufficient to change


just "one operand" in a large expression
– Must keep in mind all individual calculations
that will be performed during evaluation!
Type Casting
• Casting for Variables
– Can add ".0" to literals to force precision
arithmetic, but what about variables?
• We can’t use "myInt.0"!
– static_cast<double>intVar
– Explicitly "casts" or "converts" intVar to
double type
• Result of conversion is then used
• Example expression:
doubleVar = static_cast<double>intVar1 / intVar2;
– Casting forces double-precision division to take place
among two integer variables!
Type Casting
• Two types
– Implicit—also called "Automatic"
• Done FOR you, automatically
17 / 5.5
This expression causes an "implicit type cast" to
take place, casting the 17  17.0
– Explicit type conversion
• Programmer specifies conversion with cast operator
(double)17 / 5.5
Same expression as above, using explicit cast
(double)myInt / myDouble
More typical use; cast operator on variable
Shorthand Operators
• Increment & Decrement Operators
– Just short-hand notation
– Increment operator, ++
intVar++; is equivalent to
intVar = intVar + 1;
– Decrement operator, --
intVar--; is equivalent to
intVar = intVar – 1;
Shorthand Operators: Two Options

• Post-Increment
intVar++
– Uses current value of variable, THEN increments it
• Pre-Increment
++intVar
– Increments variable first, THEN uses new value
• "Use" is defined as whatever "context"
variable is currently in
• No difference if "alone" in statement:
intVar++; and ++intVar;  identical result
Post-Increment in Action
• Post-Increment in Expressions:
int n = 2,
valueProduced;
valueProduced = 2 * (n++);
cout << valueProduced << endl;
cout << n << endl;
– This code segment produces the output:
4
3
– Since post-increment was used
Pre-Increment in Action
• Now using Pre-increment:
int n = 2,
valueProduced;
valueProduced = 2 * (++n);
cout << valueProduced << endl;
cout << n << endl;
– This code segment produces the output:
6
3
– Because pre-increment was used
Console Input/Output
• I/O objects cin, cout, cerr
• Defined in the C++ library called
<iostream>
• Must have these lines (called pre-
processor directives) near start of file:
– #include <iostream>
using namespace std;
– Tells C++ to use appropriate library so we can
use the I/O objects cin, cout, cerr
Console Output
• What can be outputted?
– Any data can be outputted to display screen
• Variables
• Constants
• Literals
• Expressions (which can include all of above)
– cout << numberOfGames << " games played.";
2 values are outputted:
"value" of variable numberOfGames,
literal string " games played."
• Cascading: multiple values in one cout
Separating Lines of Output
• New lines in output
– Recall: "\n" is escape sequence for the
char "newline"
• A second method: object endl
• Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape
sequence "\n", skipping to next line
cout << "Hello World" << endl;
• Same result as above
Formatting Output
• Formatting numeric values for output
– Values may not display as you’d expect!
cout << "The price is $" << price << endl;
• If price (declared double) has value 78.5, you
might get:
– The price is $78.500000 or:
– The price is $78.5

• We must explicitly tell C++ how to output


numbers in our programs!
Formatting Numbers
• "Magic Formula" to force decimal sizes:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
• These stmts force all future cout’ed values:
– To have exactly two digits after the decimal place
– Example:
cout << "The price is $" << price << endl;
• Now results in the following:
The price is $78.50
• Can modify precision "as you go" as well!
Error Output
• Output with cerr
– cerr works same as cout
– Provides mechanism for distinguishing
between regular output and error output
• Re-direct output streams
– Most systems allow cout and cerr to be
"redirected" to other devices
• e.g., line printer, output file, error console, etc.
Input Using cin
• cin for input, cout for output
• Differences:
– ">>" (extraction operator) points opposite
• Think of it as "pointing toward where the data goes"
– Object name "cin" used instead of "cout"
– No literals allowed for cin
• Must input "to a variable"

• cin >> num;


– Waits on-screen for keyboard entry
– Value entered at keyboard is "assigned" to num
Prompting for Input: cin and cout
• Always "prompt" user for input
cout << "Enter number of dragons: ";
cin >> numOfDragons;
– Note no "\n" in cout. Prompt "waits" on same
line for keyboard input as follows:

Enter number of dragons: ____

• Underscore above denotes where keyboard entry


is made
• Every cin should have cout prompt
– Maximizes user-friendly input/output
Program Style
• Bottom-line: Make programs easy to read and modify
• Comments, two methods:
– // Two slashes indicate entire line is to be ignored
– /*Delimiters indicates everything between is ignored*/
– Both methods commonly used

• Identifier naming
– ALL_CAPS for constants
– lowerToUpper for variables
– Most important: MEANINGFUL NAMES!
Libraries
• C++ Standard Libraries
• #include <Library_Name>
– Directive to "add" contents of library file to
your program
– Called "preprocessor directive"
• Executes before compiler, and simply "copies"
library file into your program file
• C++ has many libraries
– Input/output, math, strings, etc.
Namespaces
• Namespaces defined:
– Collection of name definitions
• For now: interested in namespace "std"
– Has all standard library definitions we need
• Examples:
#include <iostream>
using namespace std;
• Includes entire standard library of name definitions
• #include <iostream>using std::cin;
using std::cout;
• Can specify just the objects we want
Decision Statements
• If statement
• If else statement
• Nested If statement
• Nested If-else statement
If statement

• If statement is a conditional branching


statement used to execute a set of code
when the condition is true. This belongs to
control structures.

• Syntax:
if(expression)
{
Statements
}
If Statement
If condition is true
statements

If Ali’s height is greater then 6 feet


Then
Ali can become a member of the Basket
Ball team
If Statement
If ( condition )
{
statement1 ;
statement2 ;
:
}
If statement
if (age1 > age2)
cout<<“Student 1 is older than
student 2” ;
Relational Operators
< less than
<= less than or equal to
== equal to
>= greater than or equal to
> greater than
!= not equal to
Example

if ((interMarks > 45) && (testMarks >= passMarks))


{
cout << “ Welcome to Virtual University”;
}
Example 1
• #include <iostream.h>
using namespace std;
void main()
{
int a=100;
int b=200;
if (b>a)
{
cout << "B is greater than A";
}
}
Example 2
#include <iostream.h>
main ( )
{
int AmirAge, AmaraAge;
AmirAge = 0;
AmaraAge = 0;

cout<<“Please enter Amir’s age”;


cin >> AmirAge;
cout<<“Please enter Amara’s age”;
cin >> AmaraAge;

if AmirAge > AmaraAge)


{
cout << “\n”<< “Amir’s age is greater then Amara’s age” ;
}
}
Flow Chart Symbols
Process

Flow line

Continuation mark

Decision
Flow Chart for if statement
Entry point for IF block

IF

Condition

Then

Process/
set of statement

Exit point for IF block

Note indentation from left to right


Logical Operators

AND &&
OR ||
Logical Operators
If a is greater than b
AND c is greater than d

In C
if(a > b && c> d)
if(age > 18 || height > 5)
If else statement

• If Else statement is a conditional


branching statement used to execute a set
of code when the condition is true,
otherwise executes the code in the "else"
part. This belongs to Control Structures.
if-else
if (condition)
{
statement ;
-
-
}
else
{
statement ;
-
-
}
Example
If the student age is greater than 18 or
his height is greater than five feet
then put him on the foot balll team
Else
Put him on the chess team
if-else
Entry point for IF-Else block

IF

Condition

Then

Process 1/
Set of statement

Else

Process 2
Set of statement

Exit point for IF block

Note indentation from left to right


Example 1
Code

if (AmirAge > AmaraAge)


{
cout<< “Amir is older than Amara” ;
}
else
{
cout<<“Amir is younger than Amara” ;
}
Example 2

• #include <iostream.h>
using namespace std;
void main()
{
int a=10;
int b=20;
if (a>b)
{
cout << "A is greater than B";
}
else
{
cout << "B is greater than A";
}
Unary Not operator !

 !true = false
 !false = true
Example
If (AmirAge != AmaraAge)
cout << “Amir and Amara’s Ages are
not equal”;
If (!(AmirAge > AmaraAge))

?
Nested If statement

• When an “if statement” is used within


another “if statement” ,it is called the
“nested if statement”. It is used for multi-
dimensional decision making.
Nested If statement

• Syntax:
if (condition-1)
{
if (condition-2) {
Statements-2 }
Statement-3;
}
Nested If statement
Condition-1 is tested, if
true then control goes to
next “if statement” and
condition-2 is tested.
If condition-2 is true
then statement -2 is
tested. After that control
goes to statement-3 and
this statement is
executed
If Condition-2 is false then
statement-2 is skipped and
control goes to statement-3
and will be executed.
If (age > 18)
Nested if
{
If(height > 5)
{
:
}
}
Example

/* Write a program to input three cin>>b;


integers. Compare the three integers to cout<<"Enter third integer:";
find out if they are equal. Nested if cin>>c;
statement and print the message "all
values are equal" if they are equal. if (a==b)
Otherwise print the message "these {
values are differnt“ */ if(a==c)
cout<<"All values are equal";
#include<iostream> //else
using namespace std; //cout<<"first condtion is true only";
main() }
{ int a,b,c;
cout<<"Enter first integer:"; else
cin>>a; cout<<"All values are different";
cout<<"Enter 2nd integer:"; }
Nested If-else statement

• When an “if-else statement” is used


within another “if-else statement” ,it is
called the “nested if-else statement”. It is
used for multi-selection.
Nested If-else statement

• Syntax:

if (condition-1)
Statements-1;
else if (condition-2)
Statements-2;
else if (condition-3)
Statements-3;
--------
--------
else Statement –n;
Example

/* Make a program that take student grade & else


tells him what grade he/she has achieved? if(marks>=80) {
Hint:Use Nestd if-else statement. Grade A cout<<"\nGrade ****B****\n"; }
(90-100), Grade B (80-89),Grade C(70-79), else
Grade D (60-69), if marks are less than 60
(you should take this courese again)*/ if(marks>=70)
#include<iostream> {
using namespace std; cout<<"\nGrade ***C***\n";
main() }
{ int marks=0; else
cout<<"Please enter number obtained out of if(marks>=60)
100 =\n"; {
cin>>marks; cout<<"\nGrade **D**\n";
if(marks>100||marks<0) }
cout<<"marks should be greater than 0 and
less than 100”; else
if(marks>=90) cout<<"F\t\t\t You must take this
{ cout<<"\nGrade course again";
*****A*****\n"; }
}
The switch Multiple-Selection Structure
switch ( integer expression )
{
case constant1 :
statement(s)
break ;
case constant2 :
statement(s)
break ;

...
default: :
statement(s)
break ;
}
A Switch Statement
Char ch;
Cout<<“Enter any character”;
Cin>>ch;
switch (ch)
{
case 'a': case 'A':
cout << ch << " is a vowel" << endl;
break;
case 'e': case 'E':
cout << ch << " is a vowel" << endl;
break;
.
.
.
case 'u': case 'U':
cout << ch << " is a vowel" << endl;
break;
default:
cout << ch << " is not a vowel" << endl;
}
• Write a program that input number of day of
week and displays the name of the day. For
example if user enters 1, it displays “Monday”
and so on.
Int n;
Cout<<“Enter any number”;
Cin>>n;
switch (n)
{
case 1:
cout << “Monday" << endl;
break;
case 2:
cout << “Tuesday” << endl;
break;
.
.
.
case 7:
cout << Sunday" << endl;
break;
default:
cout << “ Invalid Number”;
}
• Write a program that inputs grade of a
student and display his test score on the
following criteria:
Test Score Grade Test Score
>= 90 A >= 90
80 – 89 B 80 – 89
70 – 79 C 70 – 79
60 – 69 D 60 – 69
Below 60 F Below 60
The switch Statement
switch (grade)
{
case ‘A’:
cout << “Grade is between 90 & 100”;
break;
case ‘B’:
cout << “Grade is between 80 & 89”;
break;
case ‘C’:
cout << “Grade is between 70 & 79”;
break;
case ‘D’:
cout << “Grade is between 60 & 69”;
break;
case ‘F’:
cout << “Grade is between 0 & 59”;
break;
default:
cout << “You entered an invalid grade.”;
}
LOOP

75
Loop (Repetition Structure)

A repetition structure allows the programmer


to specify that an action is to be repeated
while some condition remains true.

76
• The Loop or group of Loops to be
repeated is called the body of the loop.

• There must be a means of exiting the loop.

77
Loop Structure

1. Control of loop: ICU


1. Initialization
2. Condition for termination (continuing)
3. Updating the condition
2. Body of loop

78
Loop Types

• the for Loop


• the while Loop
• the do-while Loop
• Nested Loop

79
for Loop

for statement executes the body of a loop for a


fixed number of times.

80
• Syntax
for (Init ; Condition; incrimination)
Action

• Example
for (int i = 0; i < 3; i++)
{
cout << "i is " << i << endl;
}

81
Ev aluated once
..
at the beginning
of the for
statements's Fo rIni t
The ForExpr is
execution ev aluated at the
start of each
iteration of the
lo op
If ForExpr is Fo rExp r
true, Action is
executed tr ue f a lse

After the Action If ForExpr is


has completed, Ac tion
false, program
the execution
PostExpression continues w ith
is ev aluated next statement

Po stEx pr

After ev aluating the


PostExpression, the next
iteration of the loop starts

82
Program to calculate the sum of odd numbers
from 1 to 10 and then print the sum on
screen.

83
main()
{
int n, sum;
sum = 0;
for(n=1; n<=10; n+2)
{
sum = sum + n;
Cout<<n<<endl;
}
cout<<“sum is =“,sum;
getch();
}

84
Write program to calculate and print the
factorial of a number.

85
main()
{
int n, k,
int fact =1;
cout<<“Enter any number”;
cin>>n;
for(k=n; k>=1; k--)
{
fact = fact * k;
}
cout<<“Factorial of <<n<<“is =“,fact;
getch();
}

86
Write a program to find a table of any number
up to 10 digits.

87
main()
{
int n, k, table;
cout<<“Enter any number”;
cin>>n;
for(k=1; k<=10; k++)
{
table = n * k;
cout<<n<<“*”<<k<<“=“<<table<<endl;
}
getch();
}

88
• Write a program that display the sum of
following series using for loop.

89
main()
{
int k;
float sum = 0.0;
for(k=1; k<=100; k++)
{
sum = sum + 1.0/k ;
}
cout<<“Sum of series is“,sum;
getch();
}

90
Write a program that finds the sum of the
square of the integers from 1 to n. Where n is
a positive value entered by the user. For
example:

91
main()
{
int k, c;
int sum = 0;
cout<<“Enter any number”;
cin>>c;
for(k=1; k<=c; k++)
{
sum = sum + (k * k);
}
cout<<“Sum of series is“<<sum;
getch();
}

92
While Loop

93
• A while loop statement repeatedly executes a
target statement as long as a given condition
is true.

94
. Expression is
evaluated at the
start of each
iteration of the
loop

Ex pres sion
If Expression is
true, Action is tr ue f a lse
executed If Expression is
false, program
Ac tion execution
continues with
next statement

95
Syntax
while(condition)
{
statement(s);
}

96
int i = 0;
while (i <= 10)
{
cout<<i;
i++;
}

97
Write a program that display counting from
1 to 10 using while loop.

98
main()
{
int n;
n = 1;
while(n<=10)
{
cout<<n<<endl;
n++;
}
getch();
}

99
• Write a program that displays first five
numbers with their squares using while loop.
1 1
2 4
3 9
4 16
5 25

100
main()
{
int n;
n = 1;
while(n<=5)
{
cout<<n<<“ “<<n * n<<endl;
n++;
}
getch();
}

101
Write a program to find a table of 2 up to 10
digits.

102
main()
{
int n,table;
int k = 1;
cout<<“Enter any number”;
cin>>n;
while(k<=10)
{
table = n * k;
cout<<n<<“*”<<k<<“=“<<table<<endl;
k = k+1;
}
getch();
}

103
• Write a program that display the sum of
following series using for loop.

104
main()
{
int k;
float sum = 1.0;
while(k <=100)
{
sum = sum + 1.0/k ;
k = k+2;
}
cout<<“Sum of series is“,sum;
getch();
}

105
NESTED LOOP
• Placing of one loop inside the body of another
loop is called nesting.

Nested Loop

• When we "nest" two loops:


– The outer loop takes control of the number of complete
repetitions of the inner loop.
– While all types of loops may be nested, the most commonly
nested loops are for loops.
Nested Loop Structure

When working with nested loops, the


outer loop changes only after the inner
loop is completely finished (or is
interrupted.).
Syntax
• The syntax for a nested for loop statement in C++
is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
}
Write a program that print the following :
1
12
123
1234
12345
123456
1234567
12345678
123456789
main()
{
for (int i=1; i<=9; i++)
{
for (int j=1; j<=i; j++)
{
cout<<j<<endl;
}
}
}
Program that print:
*
**
***
****
*****
******
*******
Write a program that print the following:

******
*****
****
***
**
*
main()
{
int i, j;
for(i = 7; i>=1; i--)
{
for(j=i; j>=1; j--)
cout<< " *<<endl;

}
getch();
}
• The syntax for a nested while loop statement in
C++ is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
}

You might also like