Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 55

Programming I (in C++)

Chapter 3:
Programming Constructs

1
06/27/2024
Outline of Topics
◦ Process of compiling and running programs
◦ Basic Elements of Programming
 Identifiers, variables, literals, constants,
keywords, comments, data types,
expressions and operators, statements.
◦ Do…s and Don’t … s

2
06/27/2024
3.1. Process of Compilation
A computer program written in a specific high
level language is called a Source Program
(Source Code).
Once the source code is prepared, it must be
translated/interpreted into the equivalent
machine code called the Executable Program.
A Compiler or an Interpreter is used for
converting source codes to Executable code.

3
06/27/2024
3.1. Process of Compilation
A compiler is a program that translates a
source program written in some high-level
programming language (such as C++) into
machine code.
The generated machine code can be later
executed many times against different data
each time.

4
06/27/2024
3.1. Process of Compilation
An interpreter reads an executable source
program written in a high-level programming
language as well as data for this program, and
it runs the program against the data to produce
some results.

Example: The Java Virtual Machine (JVM),


Unix commands

5
06/27/2024
3.1. Process of Compilation
Compile

Interpret

6
06/27/2024
3.1. Process of Compilation

The compilation process:

1. The C++ preprocessor copies the contents of


the included header files into the source code
file, generates macro code, and replaces
symbolic constants defined using #define with
their values.

7
06/27/2024
3.1. Process of Compilation
The compilation process:

2. The expanded source code file produced by the


C++ preprocessor is compiled into the assembly
language for the platform.

3.The assembler code generated by the compiler


is assembled into the object code for the
platform.

8
06/27/2024
3.1. Process of Compilation
The compilation process:

4. The object code file generated by the


assembler is linked together with the object code
files for any library functions used to produce an
executable file (see fig …)

9
06/27/2024
3.1. Process of Compilation

10
06/27/2024
3.2. Basic Elements of Programming
Every high level language has its own syntax
and semantics.
The syntax of a programming language is the
rules of the language.
The syntax of each programming language
must be precise, or the computer will not
understand the instruction and will return a
syntax error.

11
06/27/2024
3.2. Basic Elements of Programming
The semantics of a particular instruction is
what it does.
Example:
Syntax Semantics

#include<iostream.h> This example


int main() display the text
{ “Hello World”
cout<<“Hello World”;
return 0;
}

12
06/27/2024
3.2. Basic Elements of Programming
Structure (Anatomy) of a C++ program
//include headers; these are modules that include functions that //
you may use in your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream.h
#include <iostream>
using namespace std;
int main() {
//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
13
06/27/2024
3.2. Basic Elements of Programming
After you write a C++ program (the source code)
you compile it; that is, you run a compiler that
checks whether the program follows the C++
syntax
◦ if it finds errors, it lists them
◦ If there are no errors, it translates the C++
program into a program in machine language
which you can execute.

14
06/27/2024
3.2. Basic Elements of Programming
· A C++ program is a collection of one or more
subprograms, called functions.
· Roughly speaking, a subprogram or a function
(like a program) is a collection of statements
and when it is activated (that is, executed) it
accomplishes something.
· Every C++ program has a function called main.

15
06/27/2024
3.2. Basic Elements of Programming
Every programming language has facilities to:
1. Read data from some input device cin>>
2. Write output information onto an output device
cout<<
3. Perform arithmetic operations + - * /
4. Perform relational operations <= =>
5. Perform logical operations ! && ||
6. Branch to a non-sequential instruction (w/wo
structure) while
7. Store (and retrieve) data values to (and from)
memory =
16
06/27/2024
3.2. Basic Elements of Programming
Example Program:
//My first program. Prints a string on
the // user screen
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}
Output:
Welcome to C++ Programming
17
06/27/2024
3.2. Basic Elements of Programming
(1) Comments - a type of program documentation
// My comment is used for line comment
/* My comment */ is used for block comment
// indicates that the remainder of
the // line is a comment

/* comments can also look like this */


/* also
like
this
*/

18
06/27/2024
3.2. Basic Elements of Programming
(2) #include <iostream> - a preprocessor
directive
Tells the pre-processor to include in the program the
contents of the I/O stream header file called
iostream.h . This allows us to use standard stream
input and output objects like cout (displays to the
screen).
We can also use “using namespace std; ”
statement, so that we don’t have to use ugly prefixes
on cout, like “std::cout”.

19
06/27/2024
3.2. Basic Elements of Programming
(3) int main() - main function header

Every C++ program has at least one function,


called main. And there is ONLY ONE main.
Program execution begins with the first
statement in main.
(4) { brackets denote the body of
the function }

20
06/27/2024
3.2. Basic Elements of Programming
(5) ; statement terminator
Every C++ statement must end with a
semicolon.
(6) << stream insertion operator
Expression to the right of the operator is
inserted (sent) to the cout object (the display
screen).

21
06/27/2024
3.2. Basic Elements of Programming
(7) \n newline escape sequence
The backslash is an escape character. The
character following it takes on a different
meaning. E.g,
\t - tab
\a - alert; ring bell

(8) return - exits from the function


In this case control over execution is
transferred back to the operating system.
22
06/27/2024
3.2. Basic Elements of Programming
Practical

Introducing the C++ compiler

Create a new editor and type the following C++


code. Save it on your default folder, compile and
run it …

Modify the program to see other string constants …

23
06/27/2024
3.2. Basic Elements of Programming
Identifiers
 C/C++ is case-sensitive:

Sum, sum, and SUM are distinct identifiers.


By convention, if an identifier consists of two or more
words you may do one of the following:
◦ Separate the words with the underscore characters.
E.g. interest_rate, sum_of_dice
◦ Concatenate all the words and capitalize the first
character of each word except the first.
E.g. interestRate, sumOfDice

24
06/27/2024
3.2. Basic Elements of Programming
Keywords
E.g. auto, do, while, int, float, long, and const.
You are not allowed to use keywords as your own
identifiers
Standard identifiers
E.g. cout and cin
You may use a standard identifier as an identifier only
if you do not want to use the object that comes with
the compiler.

25
06/27/2024
3.2. Basic Elements of Programming
Variables and Basic Data Types
A variable has:
◦ A name,
◦ A data type
◦ And an address.

26
06/27/2024
3.2. Basic Elements of Programming

27
06/27/2024
3.2. Basic Elements of Programming
Declaration Statement
We define a variable by using the rule:
Syntax:
<data_type> <variable_name>;
E.g.
int num;
unsigned index;
bool flag;
double taxRate;

28
06/27/2024
3.2. Basic Elements of Programming
Valid Variable names in C++ satisfy the
following rule …
A variable name in C++
• uses letters, digits and the
underscore symbol (_) or any
combination of these.
• should begin with a letter or the
underscore symbol.

Example: Give some examples of valid


variables.

29
06/27/2024
3.2. Basic Elements of Programming
Note:
It is a good programming practice to follow each
variable definition with a comment in order to
remind yourself and anybody else reading the
program the purpose of that variable:

E.g.
int num, // to hold the first value
number, // to hold the second value
sum; // to hold their sum

30
06/27/2024
3.2. Basic Elements of Programming
A declaration statement tells the compiler to
reserve memory location(s) for the specified
variable(s) during program execution.

Constant Data
There are five types of constant data in C++:
• character constants,
• integer constants,
• floating-point constants,
• strings constants, and
• Boolean constants: true, false.
31
06/27/2024
3.2. Basic Elements of Programming
Character Constants:- can be printable
characters (ASCII rep) or escape sequences.

Examples of printable characters:


'A', '$', '8', ‘ ’ (space bar),
'z'
Examples of escape sequences:
'\n', '\t', '\'', '\\', ‘\”’,
'\?'

32
06/27/2024
3.2. Basic Elements of Programming
Commonly used Escape Sequences

33
06/27/2024
3.2. Basic Elements of Programming
Integer Constants
Examples: 10 -26 +9
Floating-point constants
Examples of Valid Floating-Point Constants

34
06/27/2024
3.2. Basic Elements of Programming
String constants
Examples of String Constants

35
06/27/2024
3.2. Basic Elements of Programming
Note:
• The length of a string constant is the
number of characters that it contains.

• The Null string is the string with no


character. Its length is zero.

36
06/27/2024
3.2. Basic Elements of Programming
Assignment Statement
Syntax:
<variable_name> = <value>;

E.g: Given the following declaration statements:


char letter;
int num1;
double dnum;

37
06/27/2024
3.2. Basic Elements of Programming
We can write the following assignment
statements:
letter = ‘A’;
num1 = 25;
dnum = 4.25;
num1 = 10;

Note: When you store a new value into a memory


location, any value that was previously there is
destroyed.

38
06/27/2024
3.2. Basic Elements of Programming
Initialization of of a Variable
Syntax:
<data_type> <variable_name> =
<initial-value>;
E.g. The statement:
int num1 = 25;
says the same thing as the following sequence of
two statements:
int num1;
num1 = 25;

39
06/27/2024
3.2. Basic Elements of Programming
Initial values may also be specified in a
declaration statement in which two or more
variables are defined as follows:
E.g1:
int num1 = 25,
num2,
sum = 0;
E.g2:
char letter,
grade = 'A';

40
06/27/2024
3.2. Basic Elements of Programming
Arithmetic Expressions

41
06/27/2024
3.2. Basic Elements of Programming
Rules for Evaluating Arithmetic Expressions
E.g:

42
06/27/2024
3.2. Basic Elements of Programming
Operations on Character Values
Assuming that variables ch1, ch2, ch3, and num are
defined as follows:
char ch1 = ‘P’, ch2, ch3;
int num;
The execution of the following statements will have
the specified effects:
a) ch2 = ch1 + 2; // the new value
in Ch2 is the character ‘R’
b) ch3 = ch1 - 3; // the new value
in ch3 is the character ‘M’
c) num = ‘E’ - ‘A’; // the new
value in num is the integer value 4
43
06/27/2024
3.2. Basic Elements of Programming
Arithmetic Expressions and the Assignment
Statement
General syntax of the assignment statement:
<variable-name> = <arithmetic-expression>;
E.g:
Given the following declaration of variables num1 and
num2:
int num1 = 3, num2;
the assignment statement:
num2 = num1 * 4;
will store the value 12 into the memory location that
corresponds to the variable num2.

44
06/27/2024
3.2. Basic Elements of Programming
Note: To trace the execution of one or more statements is to
show how the execution of these statements affects the contents
of memory locations.

45
06/27/2024
3.2. Basic Elements of Programming
Stream Output with cout Object
 To output means to write or to print.
 Output to the monitor may be performed by using
the output stream object cout.
 Its declaration statement is provided in the header
file iostream.
 You must include this file in any source file in which
you perform output using stream object cout.

#include < iostream>

46
06/27/2024
3.2. Basic Elements of Programming
Using cout Statements to Output String Constants
a) cout<<"Hello World!";
Output | Hello World!
b) cout<<"\nEnter a number:\t";
Output | Enter a number: _
c) cout<<"\n\nAbebe\'s tape\n";
Output | Abebe’s tape|_
d) cout<<“\nI love”<<“candies”;
Output |I lovecandies
e) cout << “\nI love”;
cout << “candies”;
Output |I lovecandies
f) cout << “\nI love” << “\ncandies”;
Output |I love
|candies
47
06/27/2024
3.2. Basic Elements of Programming
Using cout Statements to Output the Results of Arithmetic
Expressions
Assume that the variables are defined and initialized as follows:
int inum = 125;
char ch = 'Z';
float fnum = 42.75;
double dnum = 347.874;
a) cout<<"\nThe value in inum is:\t" <<
inum;
Output |The value in inum is: 125_
b) cout<<"\nI have chosen the value:\
t”<<47<<“ and the value of ch is:\t"
<<ch;
Output |I have chosen the value: 47 and the
value of ch is: Z_
48
06/27/2024
3.2. Basic Elements of Programming
c) cout<<"\nThe value of fnum is:\
t”<<fnum<<“\n and that of dnum is:\t"
<<dnum;
Output |The value of fnum is: 42.75000
|and that of dnum is: 347.8740_
d) cout<<"\n12 + 23 =\t" << (12 + 23); Output
|12 + 23 = 35_
e) cout << “\ninum - 25 =\t” << (inum - 25);
Output |inum - 25 = 100_
f) cout << inum << ch << “ ” << fnum;
Output |125Z 42.750000_

49
06/27/2024
3.2. Basic Elements of Programming
Note:
 When the name of a variable appears in a string constant, it is
not replaced by its value in the output stream.

 Arithmetic expressions are replaced with their values in the


output stream.

 Floating-point values are printed with the maximum number of


digits after the decimal point.

 In order to prevent operator precedence conflicts between the


operators in an arithmetic expression and the stream insertion
operator <<, arithmetic expressions are usually enclosed in
parentheses.

50
06/27/2024
3.2. Basic Elements of Programming

51
06/27/2024
3.2. Basic Elements of Programming

52
06/27/2024
3.2. Basic Elements of Programming

53
06/27/2024
Practical
Program Writing …

1. Write a C++ program that receives two floating point


numbers and output their Sum, Product, Difference and
Quotient.
2. Write a C++ program that receives temperature in fahr
scale and converts it to the equivalent Celsius measure.
3. Write a C++ program that receives two numbers and decide
the maximum one.
4. Write a C++ program that receives the radius of a circle
and calculates the area.

54
06/27/2024

Chapter 3: To continue …

55
06/27/2024

You might also like