0% found this document useful (0 votes)
6 views39 pages

Lec 2 (How to write a program )

The document provides a comprehensive guide on writing a C++ program, detailing the stages from writing source code in a text editor to execution by the CPU. It explains the roles of the preprocessor, compiler, linker, and loader in converting source code into an executable format. Additionally, it covers fundamental concepts such as variables, data types, operators, and basic program structure in C++.

Uploaded by

ahmedbedawy65
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)
6 views39 pages

Lec 2 (How to write a program )

The document provides a comprehensive guide on writing a C++ program, detailing the stages from writing source code in a text editor to execution by the CPU. It explains the roles of the preprocessor, compiler, linker, and loader in converting source code into an executable format. Additionally, it covers fundamental concepts such as variables, data types, operators, and basic program structure in C++.

Uploaded by

ahmedbedawy65
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/ 39

1

How to write a program

Dr. Hadeer A. Hosny


2 Points to be covered:
 How C++ program run?
 What is a Preprocessor?
 What is a Complier?
 What is a Linker?
 What is a Loader?
 Starting to write first C++ program.
 Variables
 Statements
 Operators
 Expression
How C++ program run?

 Text Editor
 Preprocessor
 Compiler
 Linker
 Loader
To convert C++ programs in to machine
language, we need:

 Text Editor
 The program is written using the text editor is known as source code.
 The source code (human readable instructions) is saved on to the secondary
storage section of the computer system (disk) with an extension ‘.cpp’ to let
the compiler know that it is written in C++ language.
 The source code needs to be grammatically correct .
What is a preprocessor?
 Preprocessor: A program that modifies the source code by adding other
files and performing various text replacements
 It executes automatically before the translation period starts.
 Examples:
 #include <iostream> adds a file called a header file to the source code. It
contains, among other things, the prototypes for cin and cout functions.
 #define PI 3.141593 replaces all instances of PI in a program with 3.141593.
 Compilation (step 3) follows immediately after the preprocessing, so, none
can access the modifications made by the preprocessor
What is a Complier?

 Compiler: translates preprocessed source code into an object code that


contains machine readable instructions
 The object code is saved on to the disk by the compiler with an extension
‘.obj’ along with the same source-code name .
 The object code is a machine code written by a format understood by
OS.
 This file is basically a binary file

Source Object
Code Compiler Code
.cpp .obj
What is a Linker?

 Linker: scans the standard library, selects the needed function


(precompiled) and upon linking them into the object file, produces an
executable file with extension ‘.exe’ (for UNIX based system it is ‘.out’)
and stores it on to the disk.
 The linker pulls everything together, makes sure that references to other
parts of the program (code) are resolved.
 Libraries are a collection of functions/objects
 Example:
 The linker adds the precompiled (in binary form) function definitions for cin,
cout, etc.
What is a Loader?

 Loader: The loader places the executable file on to the primary storage
location (RAM) of the computer system, from where the CPU executes the
program, instruction by instruction The linker pulls everything together,
makes sure that references to other parts of the program (code) are
resolved.
Example

Text Editor
/* hello.cpp */
#include <iostream>
int main() Preprocessor adds iostream text
{ (prototype for cout)
cout<<"hello world\n";
return 0;
Compiler converts to machine code
}

hello.obj Object code

Linker
-add library
-add cout object code
-add object code for
other functions

hello.exe Executable
image

Loader copies file to RAM


and CPU executes the
program when the icon is
Program Example double-clicked, for example
Basics of a Typical C++ Environment

• Phases of C++ Programs: Editor Disk


Program is created in
the editor and stored
on disk.

1. Edit Preprocessor Disk


Preprocessor program
processes the code.

Compiler creates

2. Preprocess Compiler Disk object code and stores


it on disk.

Linker links the object


code with the libraries,
3. Compile Linker Disk creates a.out and
stores it on disk

Primary
Memory
4. Link Loader

Loader puts program


in memory.
5. Load Disk ..
..
..

6. Execute Primary
Memory
CPU CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
.. executes.
..
..
11
12 Starting to write a simple C++
program.
 Let us look at a simple code that would print the words Hello
World.
1 // Fig. 1.2: fig01_02.cpp

2 // A first program in C++


13
13 Comments
3 #include <iostream> Written between /* and */ or following a //
4
Improve program readability and do not cause
the computer to perform any action
5 int main()

6 {
preprocessor directive
7 std::cout << "Welcome to C++!\n"; Message to the C++ preprocessor
8
Lines beginning with # are preprocessor
directives
9 return 0; // indicate that program #include <iostream> tells the preprocessor
ended successfully

10 }
to include the contents of the file <iostream>,
C++
whichprograms
includescontain one or
input/output more functions,
operations (such as
exactly
printingone of which
to the must be main
screen).
Welcome to C++! Parenthesis used to indicate a function
int means that main "returns" an integer value.
Prints the string ofMore
characters
in Lec contained
functions. between
return is one a way totheexit
quotation
a marks.
function. Left brace { begins the body of every
The
return 0, in this case, entire line, including std::cout, the <<
means function and a right brace } ends it
operator,
that the program terminated the string "Welcome to C++!\n" and
normally. the semicolon (;), is called a statement.

All statements must end with a semicolon.


 std::cout
 standard output stream object
 “connected” to the screen
 we need the std:: to specify what "namespace" cout
belongs to
 we shall remove this prefix with using statements
 <<
 stream insertion operator
 value to the right of the operator (right operand) inserted
into output stream (which is connected to the screen)
std::cout << " Welcome to C++!\n"

\
 escape character
 indicates that a “special” character is to be output
C++ Variables
 Variables are boxes that can hold things
 Each box has a name (“identifier”)
 Size of the box depends on the “type” of
things you are planning to put there
 You have to tell the compiler in advance
(“declare”),
 Names of each of the boxes you want
 The type of things that will go in each box
Why Use Types?
Computer sees everything in 1’s and 0’s
 “Type” is how we interpret these patterns
 What is 1101101?
 Integer (int): it is 109
 Character (char): it is ‘m’
 Floating point (float): it is 1.53x10-43

Identifier sum
Box 75 Built in type

Holds int type


Size is 32 bits (4 bytes)
Some Built Data Types
Mixing types:

avg = (a + b)/2;
avg, a and b must be same type
Exception
It is OK to mix numerical types
i.e. int, float, double
Be careful not to loose precision
Some C++ Reserved Words

bool, break, case, catch, char, class,


const, continue, default, do, double,
else, false, float, for, goto, if, int, long,
namespace, new, private, protected, public,
return, short, switch, true,
void, while
C++ Statements

One C++ instruction that ends with a semicolon


 sum = a + b;
 float temp_c;
 float temp_f;

Can take more than one line


 int sum, a,
b;
Declaration statement
 int sum;
Assignment statement
 sum =0;
Compound Statements

 Use { and } to group


any number of {
statements cout << “Hello”;
 This block is treated as return 0;
one statement
}
 Used always with:
 Loop
 Condition
 Function
 Class
 Others
#include
18- <iostream> Pre-processor directives
Feb-
using
25 namespace std; “using” directives

// entry point
int main() main: single C++ statement !
{
float w_lb, w_kg; A declaration statement

cout << "Enter weight (lb): ";


cin >> w_lb;

w_kg = w_lb * 0.454; An assignment statement


cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
#include <iostream>
// without “using namespace std;”

// entry point
int main()
{
float w_lb, w_kg;

std::cout << "Enter weight (lb): ";


std::cin >> w_lb;

w_kg = w_lb * 0.454;


std::cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
Symbolic Constants

 Variables that won’t let you change the initial value


 So, they must be given a value in its declaration
 As a matter of style, names are all caps
 E.g. const double PI =3.14;
 Always use to these to represent numeric values
within your program
 Or for anything that you know will not change
Calculating Things

Using calculator
 4-2+5-1 = ?
 +, - *, / and = are the operators
 3+2*5 vs (3+2)*5
Need to consider operator precedence
 * and / have higher precedence than +, -
 C++ operators have these and more
C++ Operators

 Operators take one or more input values and


produce one output value
 E.g. + , - , * , / , < , > , <= , >= , && , ||
 Operators come in two types
 Unary operators – take one input value
 Binary operators – take two input values
C++ Operator Map

Operators
Binary Unary
Arithmetic Logical Bitwise Comparison Arithmetic
+ add && and & and < - less-than ++ increment
- sub || or | or > - gt.-than --decrement
* mul ^ xor <= - less-or-eq
/ div >= - gt-or-eq
% mod Copy == - equal
= Logical
!= - not-equal ! not
+=, -=, *=, /=, %=

Pointer * , &
Unary Operators
int a=9;
 Negative: -a gives -9
 Logical-invert: !a gives 0
 * and & are pointer operations
 Increment: ++
 Decrement: --
More Unary Expressions
int a=9, b;

 Pre-Increment :
 b = ++a; b is 10 and a is 10
 Post-Increment:
 b = a++; b is 9 and a is 10
 Pre-Decrement :
 b = --a; b is 8 and a is 8
 Post-Decrement:
 b = a--; b is 9 and a is 8
Arithmetic Operators: + - * / %

 a+b, a-b, a*b, a/b


 Integer division: 11/4 gives 2
 Floating point division:
 11.0/4 gives 2.75
 Modulo operator: % (only for integers)
 11%4 gives 3
 10%5 gives 0
Copy Operator (Assignment operator)

 Simple copy: a = b;
 Overwrites the left object (l-value) with the result of the expression
on the right (r-value)
 l-value must be writable
 Copy with add
 a += b; is the same as a = a + b;
 Other copy-with-subtract, multiplication, division behaves the
same
 a -= b; a *= b; a /= b; etc
Comparison Operators

 < , > , =<, =>, ==, !=


 All yield Boolean true (1) or false (0)
 11<4 is false. 11<11 is false
 11>4 is true. 11>11 is false
 11>=11 and 11<=11 both are true
 4==4 is true. 4!=4 is false
 Don’t use floating-point values with == or !=
Logical Operators

 Logical AND: &&


 exp1 && exp2 && exp3 && exp3
 Yields true if all the expressions are true
 If an expression is false, skips the rest
 Logical OR: ||
 exp1 || exp2 || exp3 || exp3
 Yields true if any expression is true
 If an expression is true, skips the rest
 These are called “short-circuit” operators
Examples of Logical Operators

 (-6<0)&&(12>=10) true && true


results in true

 (3.0 >= 2.0) || (3.0 >= 4.0)


true || false
results in true
 (3.0 >= 2.0) && (3.0 >= 4.0)

true && false


results in false
Expressions

 A series of operators x3 4


and their inputs 
 E.g. x+3-y+5 5 y3
 Evaluated from left-to- is not the same as
right
 Be careful with division x  3/ 5  4 / y  3
 Pay attention to
operator precedence Correct form:
(x+3)/5 + 4/(y+3)
Operator Precedence

 Use parenthesis if you are not sure!


 Unary (++, --, !, -)
 Arithmetic (*, /, %, +, -)
 Comparison (< , <= , > , >=, ==, !=)
 Logical (&&, ||)
 Assignment (= , +=,-=,*= ,/= ,%=, etc)
Expression Examples

3y
 2*x*x-3*y/5*y+6 2x 
2
y6
 Should really be 5
 2*x*x-(3*(y/5)*y)+6

2x  3y
2
 (2*x*x-3*y)/(5*y+6)
5y  6
Expressions With Side Effects

 r = x + y--; is equivalent to
 r = x + y; y = y-1; (two actions!)
 r = ++x - y; is equivalent to
 x = x+1; r = x - y; (two actions!)
 Keep it simple
 Not r = --x + y++;
39

You might also like