1
HOW TO WRITE A
PROGRAM
DR. SAMAR A. SAID
First term
2023-2024
POINTS TO BE COVERED:
• How C++ program run?
• What is a Text editor?
• 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
2
HOW C++ PROGRAM RUN?
• To convert C++ programs in to machine language, we need:
• 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.
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.
• Compilation (step 3) follows immediately after the preprocessing, so, none can
access the modifications made by the preprocessor
What is a Complier?
• Compiler: In this stage of any C/C++ program execution process, the
compiler will compile the program, checks the errors and generates the object
file (this object file contains assembly code).
• 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: in this stage Linker links the more than one object files or libraries
and generates the executable file.
• 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.
• Libraries are a collection of functions/objects
• Example:
• The linker adds the precompiled function definitions for cin, cout, etc.
What is a Loader?
• Loader: This is a final stage of any C/C++ program execution process, in this
stage Loader loads the executable file into the main/primary memory. And
program run.
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
Starting to write a simple C++ program.
• Let us look at a simple code that would print the words hello world.
10
1 // Fig. 1.2: fig01_02.cpp
2
11//
11
A first program in C++
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
#include <iostream> tells the preprocessor to
9 return 0; // indicate that program include
endedthe contents of the file <iostream>, which
successfully
10 }
includes input/output operations (such as printing to
C++ programs contain one or more functions, exactly
the screen).
one of which must be main
Welcome to C++! Parenthesis used to indicate a function
int means that main "returns" an integer value.
Prints the string of characters
More in Leccontained
functions.between the
return is one a way toquotation
exit a marks.
function. Left brace { begins the body of every function
return 0, in this case, The entire
means thatline, including std::cout, the << operator,
and a right brace } ends it
the program terminated the string "Welcome to C++!\n" and the
normally.
semicolon (;), is called a statement. 11
All statements must end with a semicolon.
• Std::cout
• std is an abbreviation of "standard".
• std is the "standard namespace" . cout , cin and a lot of other
functions are defined within it.
• The cout is a predefined object of ostream class, and it is used
to print the data on the standard output device.
• We need the std:: to specify what "namespace" cout belongs to
• We shall remove this prefix with using statements
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
• Variable name must begin with a letter
• A variable name can only contain alpha-numeric characters and
underscores
• Variable are case sensitive
• You cannot use reserve words to name variables
• Use variable names that describe the value
• The type of things that will go in each box
• In next slide
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
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 { } to group any
{
number of statements
cout << “hello”;
• This block is treated as one
statement return 0;
}
• Used always with:
• Loop
• Condition
• Function
• Class
• Others
#include
29- <iostream> Pre-processor directives
Dec-
using
23 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
• Always use to these to represent numeric values within your
program Or for anything that you know will not change
• E.G. Const double PI =3.14;
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 - negative
- sub || or | or > - gt.-than - ++ increment
* mul ^ xor <= - less-or-eq --decrement
/ div >= - gt-or-eq
% mod Copy == - equal
= Logical
!= - not-equal ! not
+=, -=, *=, /=, %=
Pointer * , &
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)
• 9%2 gives 1
• 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
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
OPERATOR PRECEDENCE
• Use parenthesis
• Unary (++, --, !, -)
• Arithmetic (*, /, %, +, -)
• Comparison (< , <= , > , >=, ==, !=)
• Logical (&&, ||)
• Assignment (= , +=,-=,*= ,/= ,%=, etc)
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!)
32
INPUT AND OUTPUT
DR. Samar A. Said
First term
2023-2024
USING STANDARD UTILITIES
• C++ compilers comes with a vast collection of utilities: i/o,
math etc
• This is called the “standard library”
• You need to:
• Include proper header files. E.G. #Include<iostream>
• Use using namespace std; statement
• Or use std:: prefix
STANDARD INPUT AND OUTPUT
• Called the i/o stream objects
• #Include <iostream>
• Input is usually from keyboard
• Output is usually to a console window
• Cout object is the output stream (ostream)
• Cin object is the input stream (istream)
PRODUCING OUTPUT WITH COUT
• Cout
• Is an ostream object
• Streams output to standard output
• Uses the << (output) operator
• General form:
• Cout << expression << expression;
• Note: an expression is any C++ expression (string constant, identifier,
formula or function call)
//Example1 for input and output
#include <iostream>
#include <string> 1
using namespace std;
int main() 2
{ 4.5
int i, j; output
double x;
string units = “ cm”; 1,2,
cin >> i >> j; 4.5 cm
cin >> x;
cout << “output \n”;
cout << i << ‘,’ << j << ‘,’ << endl
<< x << units << endl;
return 0;
} // Input stream:
1 // Fig. 1.4: fig01_04.cpp
2 // Printing a line with multiple statements
3 #include <iostream>
5 int main()
1. Load
<iostream>
6 {
7 std::cout << "Welcome ";
8 std::cout << "to C++!\n"; 2. main
9
10 return 0; // indicate that program ended successfully
2.1 Print
11 } "Welcome"
Welcome to C++! 2.2 Print "to
C++!"
Unless new line '\n' is specified, the text continues on
the same line.
2.3 newline
37
2.4 exit (return
0)
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream>
4 1. Load <iostream>
5 int main()
2. main
6 {
7 std::cout << "Welcome\nto\n\nC++!\n"; 2.1 Print "Welcome"
8
9 return 0; // indicate that program ended successfully
2.2 newline
10 }
2.3 Print "to"
Welcome 2.4 newline
to
C++! 2.5 newline
Multiple lines can be printed with one
2.6 Print "C++!"
statement
2.7 newline
38
2.8 exit (return 0)
MATH FUNCTIONS WITH <CMATH>
abs(x) computes absolute value of x
sqrt(x) computes square root of x, where x >=0
pow(x,y) computes xy
ceil(x) nearest integer larger than x
floor(x) nearest integer smaller than x
exp(x) computes ex
log(x) computes ln x, where x >0
log10(x) computes log10x, where x>0
TRIGONOMETRIC FUNCTIONS
sin(x) sine of x, where x is in radians
cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians
asin(x) sine-1(x), returns angle in radians [-π/2, π/2]
acos(x) cosine-1(x), returns angle in radians [0,π]
atan(x) tan-1(x), returns angle in radians [-π/2, π/2]
atan2(y,x) tan-1(y/x), returns angle in radians [-π, π]
sinh(x) Hyperbolic sine of x
cosh(x) Hyperbolic cosine of x
tanh(x) Hyperbolic tan of x
OUTLINE OF COURSE
• CONTENTS GOING TO BE COVERED DURING COURSE:
• INTRODUCTION
• NUMBERING SYSTEMS
• NEGATIVE NUMBERS AND ADDING IN BINARY
• BOOLEAN ALGEBRA
• FLOW CHART, PSEUDO CODE, AND ALGORITHM
• HOW TO WRITE A C++ PROGRAM.
• INPUT AND OUTPUT
• CONDITIONS
• LOOPS
• ARRAY