0% found this document useful (0 votes)
35 views

My First Program in C++ #Include Int Main (Std::cout Using Namespace STD Int Main (Cout "Hello World!" )

The document describes a simple "Hello World!" program written in C++. It includes the necessary header file, declares the main function which contains a single line of code to print "Hello World!" to the standard output stream.

Uploaded by

douaa jazzar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

My First Program in C++ #Include Int Main (Std::cout Using Namespace STD Int Main (Cout "Hello World!" )

The document describes a simple "Hello World!" program written in C++. It includes the necessary header file, declares the main function which contains a single line of code to print "Hello World!" to the standard output stream.

Uploaded by

douaa jazzar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

// my first program in C++

#include <iostream>

int main()
{
std::cout << "Hello World!";
}

// my first program in C++


#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
}
C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

address
float double long double

pointer reference
Premitive Data Types in C++
• Integral Types
• represent whole numbers and their negatives
• declared as int, short, or long
• Character Types
• represent single characters
• declared as char
• Stored by ASCII values
• Boolean Type
• declared as bool
• has only 2 values true/false
• will not print out directly
• Floating Types
• represent real numbers with a decimal point
• declared as float, or double
• Scientific notation where e (or E) stand for “times 10 to the ” (.55-e6)
Samples of C++ Data Values
int sample values
4578 -4578 0

bool values
true false

float sample values


95.274 95.0 .265

char sample values


‘B’ ‘d’ ‘4’ ‘?’ ‘*’
What Does a
Variable Declaration Do?
• A declaration tells the compiler to allocate enough memory to hold
a value of this data type, and to associate the identifier with this
location.
• int ageOfDog;→
• char middleInitial; →
• float taxRate;→
Assignment Operator Mechanism
• Example:
0
int count = 0;
int starting; 12345 (garbage)
starting = count + 5;
• Expression evaluation:
• Get value of count: 0
• Add 5 to it.
• Assign to starting
5
Arithmetic Operators
• Operators: +, -, * /
• For floating numbers, the result as same as Math operations.
• Note on integer division: the result is an integer. 7/2 is 3.
• % (remainder or modulo) is the special operator just for integer. It
yields an integer as the result. 7%2 is 1.
• Both / and % can only be used for positive integers.
• Precedence rule is similar to Math.
Arithmetic Expressions
• Arithmetic operations can be used to express the
mathematic expression in C++:

b 2 − 4ac b *b − 4* a *c
x( y + z ) x * ( y + z)
1
1 /( x * x + x + 3)
x2 + x + 3
a+b (a + b) /(c + d )
c−d
Simple Flow of Control
• Three processes a computer can do:
• Sequential
expressions, insertion and extraction operations
• Selection (Branching)
if statement, switch statement
• Repetition/Iteration (Loop)
while loop, do-while loop, for loop
bool Data Type
• Type bool is a built-in type consisting of just 2 values, the constants
true and false
• We can declare variables of type bool
bool hasFever; // true if has high temperature
bool isSenior; // true if age is at least 55
• The value 0 represents false
• ANY non-zero value represents true
Boolean Expression
• Expression that yields bool result
• Include:
6 Relational Operators
< <= > >= == !=
3 Logical Operators
! && ||
Relational Operators
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7
y=x<3 0
y=x>3 1
Simple if Statement

• Is a selection of whether or not to execute a statement or a block of


statement.
TRUE
expression

statement(s) FALSE
Simple if Statement Syntax
if (Boolean Expression)
Statement

if (Bool-Expr)
{
Statement_1

Statement_n
}
If-else Statement
• provides selection between executing one of 2 clauses (the if clause
or the else clause)

TRUE FALSE
expression

if clause else clause


Use of blocks
• Denoted by { .. }
• Recommended in controlled structures (if and loop)
• Also called compound statement.

if (Bool-Expression )
{
“if clause”
}
else
{
“else clause”
}
Loop
• is a repetition control structure.
• causes a single statement or block of statements to be executed
repeatedly until a condition is met.
• There are 3 kinds of loop in C++:
• While loop
• Do-While loop
• For loop
While Loop
SYNTAX
while ( Expression )
{
… // loop body
}
• No semicolon after the boolean expression
• Loop body can be a single statement, a null statement, or a block.
While Loop Mechanism
• When the • When the
expression is expression is
tested and tested and
found to be FALSE
found to be
false, the loop Expression
is exited and true, the loop
control passes body is
TRUE
to the executed.
statement Then, the
body
which follows expression is
statement
the loop body. tested again.
While Loop Example
int count ;
count = 0; // initialize LCV
while (count < 5) // test expression
{
cout << count << “ ”; // repeated action
count = count + 1; // update LCV
}
cout << “Done” << endl ;
Increment and Decrement Operators
• Denoted as ++ or --
• Mean increase or decrease by 1
• Pre increment/decrement: ++a, --a
• Increase/decrease by 1 before use.
• Post increment/decrement: a++, a--
• Increase/decrease by 1 after use.
• Pre and Post increment/decrement yield different
results when combining with another operation.
Pre and Post Increment and Decrement
int count ; count Expression Output
count = 0; 0 true 0
while (count < 5) 1 true 01
{ 2 true 012
cout << count++ << “ “ ; 3 true 0123
} 4 true 01234
cout << “Done” << endl ; 5 false 0 1 2 3 4 Done
int count ; count Expression Output
count = 0; 0 true 1
while (count < 5) 1 true 12
{ 2 true 123
cout << ++count << “ “ ; 3 true 1234
} 4 true 12345
cout << “Done” << endl ; 5 false 1 2 3 4 5 Done
Do-While Loop
SYNTAX
do
{
… // loop body
} while ( Expression );
• Insured that the loop is executed at least once
• Boolean expression is tested at the end of the loop.
Do-While Loop Mechanism
• The loop body is executed first

• When the • When the


expression is expression is
tested and tested and
found to be body
found to be
false, the loop statement
true, the loop
is exited and body is
control passes executed.
to the FALSE TRUE
statement Then, the
Expression expression is
which follows
the loop body. tested again.
Do-While Loop Example
int ans;
do
{
cout << “Choose a number from 1 to 4: “;// repeated action
cin >> ans; // LCV is initialized or updated
} while (ans >= 1 && ans <= 4); // test expression
cout << “Done”;

Output Input ans Expression


Choose a number from 1 to 4: 2 2 true
Choose a number from 1 to 4: 3 3 true
Choose a number from 1 to 4: 1 1 true
Choose a number from 1 to 4: 5 5 false
Done
BREAK statement
allows to exit from any loop.

do
{
cin>>x;
if (x % 2 ==0)
break;
} while (x > 0); // exits when an even number is entered
CONTINUE Statement
allows you to skip the rest of the loop body and go
back to the beginning of the loop.

do
{
cin>>x;
if (x % 2 == 0)
continue;
cout<<x<<endl;
} while (x <100);
//prints out all odd numbers entered less than 100
For loop statement
// countdown using a for loop // countdown using a for loop
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main ()
{
int main ()
for (int n=10; n>0; n--) {
{ for (int n=10; n>0; n--, cout<<n<<“,”)
cout << n << ", "; {}
} cout << "\n";
cout << "\n"; }
}
Writing into a file
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Reading from a file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ifstream myfile;
myfile.open (“myfile.txt");
While( !myfile.eof() )
{
Myfile>>x>>y>>z;
}
myfile.close();
return 0;
}
Functions
• segments of code to perform individual tasks
// function example
#include <iostream>
using namespace std;

int addition (int a, int b)


{
int r;
r=a+b;
return r;
}

int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
Void functions, no return value
// void function example
#include <iostream>
using namespace std;

void printmessage ()
{
cout << "I'm a function!";
}

int main ()
{
printmessage ();
}
Arguments by value and by reference
void exchange(int a, int b)
{
int c=a;
a=b;
b=c;
}
int main()
{
int a = 1;
int b = 2;
cout<<a<<“ “<<b<<endl;
exchange(a,b);
cout<<a<<“ “<<b<<endl;
}
Arguments by value and by reference
void exchange(int& a, int& b)
{
int c=a;
• Faster execution
a=b;
• Memory saving
b=c;
} • Allows function to return
int main() more than one value
{
int a = 1;
int b = 2;
cout<<a<<“ “<<b<<endl;
exchange(a,b);
cout<<a<<“ “<<b<<endl;
}
Inline functions
inline int add (int a, int b)
{
return a+b;
}

• More efficient for short functions, because it suggests to the compiler


that the code generated by the function body shall be inserted at
each point the function is called, instead of being invoked with a
regular function call inducing other operations (jumps and arguments
stacking…)
Default values
#include <iostream>
using namespace std;

int divide (int a, int b=2)


{
int r;
r=a/b;
return (r);
}

int main ()
{
cout << divide (12) << '\n';
cout << divide (20,4) << '\n';
return 0;
}
Recursive functions
// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)


{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}

int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}
// overloading functions
Overloaded functions #include <iostream>
using namespace std;

• In C++, two different functions can int operate (int a, int b)


{
have the same name if their return (a*b);
parameters are different; either }

because they have a different double operate (double a, double b)


number of parameters, or because {
return (a/b);
any of their parameters are of a }
different type.
int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout << operate (x,y) << '\n';
cout << operate (n,m) << '\n';
return 0;
}
Function templates
// overloaded functions // function template
#include <iostream> #include <iostream>
using namespace std; using namespace std;
If the body of the template <class T>
int sum (int a, int b) function will remain
{ T sum (T a, T b)
return a+b; the same while {
} overloading, it is T result;
more convenient to result = a + b;
double sum (double a, double b) define it as a return result;
{ }
template function
return a+b;
} int main () {
int i=5, j=6, k;
int main () double f=2.0, g=0.5, h;
{ k=sum<int>(i,j);
cout << sum (10,20) << '\n'; h=sum<double>(f,g);
cout << sum (1.0,1.5) << '\n'; cout << k << '\n';
return 0; cout << h << '\n';
} return 0;
}
Multiple template parameters
// function templates
#include <iostream>
using namespace std;

template <class T, class U>


bool are_equal (T a, U b)
{
return (a==b);
}

int main ()
{
if (are_equal(10,10.0)) Automatic data type
cout << "x and y are equal\n";
else
cout << "x and y are not equal\n";
return 0;
}
Local and global variables
int foo; // global variable

int some_function ()
{
int bar; // local variable
bar = 0;
}

int other_function ()
{
foo = 1; // ok: foo is a global variable
bar = 2; // wrong: bar is not visible from this function
}

You might also like