C Revision
C Revision
(HTI)
Mechatronics Department
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"
• 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
• 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
• 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
• Syntax:
if(expression)
{
Statements
}
If Statement
If condition is true
statements
Flow line
Continuation mark
Decision
Flow Chart for if statement
Entry point for IF block
IF
Condition
Then
Process/
set of statement
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
Condition
Then
Process 1/
Set of statement
Else
Process 2
Set of statement
• #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
• 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
• Syntax:
if (condition-1)
Statements-1;
else if (condition-2)
Statements-2;
else if (condition-3)
Statements-3;
--------
--------
else Statement –n;
Example
...
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)
76
• The Loop or group of Loops to be
repeated is called the body of the loop.
77
Loop Structure
78
Loop Types
79
for Loop
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
Po stEx pr
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
******
*****
****
***
**
*
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);
}
}