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

Chapter 2 Fundamentals of Programming22222222

The document provides an overview of C++ programming basics, including the structure of a C++ program, the role of functions, and the importance of the main function. It explains the use of variables, constants, and data types, as well as input/output operations through console using cout and cin. Additionally, it covers operators, expressions, and the significance of syntax elements like semicolons and curly braces.

Uploaded by

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

Chapter 2 Fundamentals of Programming22222222

The document provides an overview of C++ programming basics, including the structure of a C++ program, the role of functions, and the importance of the main function. It explains the use of variables, constants, and data types, as well as input/output operations through console using cout and cin. Additionally, it covers operators, expressions, and the significance of syntax elements like semicolons and curly braces.

Uploaded by

evercage103
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Fundamentals of Programming

C++
1
Chapter Two
• C++ Programming Basics
– A computer program is a set of instructions
that a programmer writes to tell a computer
how to carry out a certain task.
– The instructions, however, must be in a
language that the computer understands.
– Computers understand only binary language
i.e. that composed of 1’s and 0’s. This is a
low- level language & very hard to program in.
– So high-level languages such as C++ or
Pascal were discovered to make the
programming task easier.

2
Integrated Development Environment
(IDE)
Editor

Source file Header files

compiler

Object file Standard library

linker Other libraries


&
Object files
Executable file

3
Executable
• An executable is a file that your computer can.
• A computer program like Microsoft Word is an
executable.
• To make an executable, you need a compiler, which is a
program that turns source code into an executable.
• an editor makes it possible for you to create source code
in the right format.
• For Windows, you'll get up with a sophisticated editor,
known as an integrated development environment (IDE)
that combines an editor with a compiler.

4
Function
• A function is a piece of code that is written possibly with simply
basic language features.
• The main function is a special function.
• It's the only function that must be included in all C++ programs, and
it's the point where your program will start when you run it.
• The main function is preceded by the type of its return value, int.
• When a function returns a value, the code that calls that function will
be able to access the value returned from the function. In the case
of main, the value returned goes to the operating system. Normally
we would need to explicitly return a value here, but C++ allows the
main function to omit the return statement and it will default to
returning 0 (a code that tells the operating system everything went
OK).

5
Curly braces

• The curly braces, { and }, signal the beginning and end


of functions
• You can think of them as meaning begin and end.

Semicolon
• The semicolon is part of the syntax of C++.
• It tells the compiler that you're at the end of a statement.
• The semicolon is used to end most statements in C++.

6
#include <iostream>
• is an include statement that tells the compiler to put code from the
header file called iostream into our program before creating the
executable.
• The iostream header file comes with your compiler and allows you
to perform input and output.
• Using #include effectively takes everything in the header file and
pastes it into your program. By including header files, you gain
access to the many functions provided by your compiler.

7
The basic structure of a C++ program

1. [include statements]
2. using namespace std;
3. int main()
4. {
5. [your code here];
6. return 0;
7. }

8
A (Very) Simple C++ Program

Probably the best way to start learning a programming


language is by writing a program. Therefore, the above shall
be our first program.

9
Structure of a C++ Program

 Comments are parts of the source code disregarded by the compiler.


 They simply do nothing.
 Their purpose is only to allow the programmer to insert notes or descriptions
embedded within the source code.
C++ supports two ways to insert comments:

1. The first of them, known as line comment, discards everything from where the
pair of slash signs (//) is found up to the end of that same line.
2. The second one, known as block comment, discards everything between the /*
characters and the first appearance of the */ characters, with the possibility of
including more than one line.
10
Structure of a C++ Program

#include; preprocessor directive used to add library files


(predefined header file)
Lines beginning with a hash sign (#) are preprocessor directives. They are
not regular code lines with expressions but indications for the compiler's
preprocessor. In this case the directive #include<iostream> tells the
preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output
library in C++, and it is included because its functionality is going to be
used later in the program. 11
Structure of a C++ Program

All the elements of the standard C++ library are declared within what is
called a namespace, the namespace with the name std. So in order to
access its functionality we declare with this expression that we will be using
these entities.

12
Structure of a C++ Program

This line corresponds to the beginning of the definition of the main function.
The main function is the point by where all C++ programs start their execution,
independently of its location within the source code. It is essential that all C++
programs have a main function.
The word main is followed in the code by a pair of parentheses (()).
Right after these parentheses, we can find the body of the main function
enclosed in braces ({}). What is contained within these braces is what the
function does when it is executed.
13
Structure of a C++ Program

This line is a C++ statement. A statement is a simple or compound expression


that can actually produce some effect. In fact, this statement performs the
only action that generates a visible effect in our first program. A statement
ends with a semicolon character (;).
Note that cout is included within the std namespace of the iostream standard
file and is used to display characters in the standard output stream like the
computer monitor, for example.

14
Structure of a C++ Program

The return statement causes the main function to finish. return may be
followed by a return code (in our example is followed by the return code with a
value of zero). A return code of 0 for the main function is generally interpreted
as the program worked as expected without any errors during its execution. This
is the most usual way to end a C++ console program.

15
Structure of a C++ Program

You may have noticed that not all the lines of this program perform actions
when the code is executed.
There were lines containing only comments (those beginning by //).
There were lines with directives for the compiler's preprocessor (those
beginning by #).
Then there were lines that began the declaration of a function (in this case, the
main function) and, finally lines with statements (like the insertion into cout),
which were all included within the block delimited by the braces ({}) of the
main function.
16
The program has been structured in different lines in order to
be more readable, but in C++, we do not have strict rules on
how to separate instructions in different lines. For example,
instead of:

We could have written:

All in just one line and this would have had exactly the same
meaning as the previous code. 17
In C++, the separation between statements is specified with an ending
semicolon (;) at the end of each one, so the separation in different
code lines does not matter at all for this purpose.

We can write many statements per line or write a single statement that
takes many code lines.
The division of code in different lines serves only to make it more
legible and schematic for the humans that may read it.
Let us add an additional instruction to our first program:

18
Note that the result is the same for all the following…

19
Practice problems

1. Write a program that prints out your name.


2. Write a program that displays multiple lines of text
onto the screen, each one displaying the name of
one of your friends.
20
Built-in Data Types
 A built-in data type is a
data type for which the
programming language
provides built-in support.
 Data used by our
program are stored in the
computer memory.
 But the computer must
know what we want to
store in the memory.
 since storing a simple
number, a letter or a large
number is not going to
occupy the same space
in the memory.
21
 Some of them are:
22
Integral types

23
Floating pt types
 Floating-Point types: - float, double, and long double
 double uses twice as many bytes as float.
 float => 4 bytes, double => 8 bytes, & long double => 8, 10, 12, or
16 bytes.
 float :- 4 byte  3.4E+/-38 (7 digits)
 double :- 8 byte  1.7E+/-308 (15 digits)
 long double :- 10 byte  1.2E+/-4932 (19 digits)
 The unsigned types are used when the quantities represented are
always positive.

24
White characters/Escape sequences [special characters]
• A backslash, \ , preceding a character tells the compiler that the sequence
following the backslash does not have the same meaning as the character
appearing by itself. Such a sequence is called an escape sequence.

25
Variables and Constants
 A variable in c++ is something that stores data.
X
 The value of a variable can be changed during the program
execution => content of a variable is changeable, not fixed.
 But before you use a variable you have to declare it.
 The purpose of declaring a variable is to let the computer know
that you are going to use it so the computer can set aside enough
memory to store its value.
 C++ is Case sensitive Ex.RESULT is not the same as the
variable result nor the variable Result.
 Its syntax is: type identifier;
Example: int age;
float rate,radius,salary;
double AreaOfCircle;
26
Continued…
 Different types of variables require different amounts
of memory.
Example: integer------2 bytes
float------4 bytes
char------1 byte
 Variables can be initialized at the same time
they are declared
Example:
float sum=0;
int age(25);
double rate=0.75;

27
#include<iostream>
using namespace std;
int main()
{
int radius=5; //assigning value to the variable
float PI=3.14;
float area;
area=PI*radius*radius;//area of circle=πr2
cout<<“Area = ”<<area;
return 0;
}

28
29
Constants
• A constant is any expression that Constants can be
has fixed value through out the defined or declared:
whole program. Defined
• Constants can be integers, #define x 35
floating-point numbers, #define y 390
characters and strings
Example:
152, -63 (integers)
3.14159, 6.02E23, 0.2 #define y ‘c’
(floating point numbers)
‘z’, ‘B’, ‘h’ (characters)
declared
“First Name”, “This is a
string” (strings)
const int y=9;
const float PI=3.14139;
30
Find the error of this program
#include <iostream>
using namespace std;
const int Y=9;
void main()
{
cout<<3*Y\n;
y=y+9;
cout<<Y;
} //error b/c we are trying to change constant
variable y
31
Identifiers
• Identifiers are valid names that are used to
represent variables, constants and functions
• When choosing valid identifiers for your
constants, variables and functions, the
following rules apply.
– An identifier contains a series of
letters, numbers, or underscore(_)
– The first character must be a
letter or underscore

32
– No restriction on the length of the
identifier
– C++ keywords are reserved and can
not be used as identifiers
C++ keywords:

33
Valid identifiers Invalid identifiers
a gotoC++ keyword
_var US$
B12 586_cpu
top_of_window true C++ keyword

Set_Text_Color object-oriented
a_very_long_name1234567

34
cout<< and cin>>
• Is Communication through console [Input /output]
• cout<< is used to write strings or characters in to the console O/P
• Example:
• cout<<“Enter radius:”; ";// prints Output sentence on screen
• cout << 120; // prints number 120 on screen
• cout << x; //prints the content of variable x on screen
• cout << ‘x’; //prints character or letter x on the screen
• NB: the difference between x and 'x'
• x refers to variable x, whereas 'x' refers to the character
constant 'x'
• cin>> is used to read data from the console and it stands for
console input
• Example:
• cin>>rad; 35
Example:
#include<iostream>
using namespace std;
int main()
{
const float PI=3.14;
float rad;
float area=0;
cout<<“Enter radius:”;
cin>>rad;
area=PI*rad*rad;
cout<<“The area is:”<<area;
return 0;
36
}
Insertion & Extraction operators
 The Extraction operator (>>) or insertion operator (<<)may be
used more than once in a same sentence:
 Ex1. cout << "Hello, " << "I am " << "a C++ sentence";
 output: Hello, I am a C++ sentence
 Ex2. int age=25, pobox=25276; cout << "Hello, I am " << age
<< " years old and my p.o.box is " << pobx;
 output:Hello, I am 25 years old and my p.o.box is
25276
 cin can only process the input from the keyboard once the
RETURN key has been pressed.
 You can also use cin to request more than one datum input
from the user:
 cin >> a >> b; is equivalent to:
 cin >> a;
37
 cin >> b;
Operators
 Once we know of the
existence of variables
and constants we can
begin to operate with
them.

 1. Arithmetic Operators

38
• Divisions performed with integral operands
will produce integral results.
example: 7/2 computes to 3
• If at least one of the operands is a floating-
point number, the result will also be a floating-
point number.
example: 7.0/2 computes 3.5
• Remainder division is only applicable to
integral operands and returns the remainder of
an integral division.
example: 7%2 computes to 1
39
• Expressions
In its simplest form an expression consists
of only one constant, one variable, or one
function call.
int a=4;
double x=7.9;
a * 512 // Type int
1.0 + sin(x) // Type double
x – 3 // Type double
40
2. Assignment operator (=)
• Simple assignments:
z = 7.5;
y = z;
x = 2.0 + 4.2 * z;
• Compound assignments (+=, -=, *=, /=, %=)
i += 3; is equivalent to i = i + 3;
i *= j + 2; is equivalent to i = i * (j+2);

41
3. Increment & Decrement Operator
• Pre-increment (++i Or --i) : i is incremented or decremented
first and the new value of i is then applied respectively
Example: int i=5;
int x=2*++i;
cout<<x; //12
cout<<i; //6
• Post-increment (i++ Or i--): the original value of i is applied
before i is incremented or decremented respectively.
Example: int i=5;
int x=2*i++;
cout<<x; //10
cout<<i; //5
N.B ++i or i++=> i=i+1 & --i or i--=> i=i-1 after being applied.
42
Examples
int x=5; int x=9, y=4; int i=2, j=8;
--x; cout<<x--<<" <<+ cout<<i++<<endl; // Output: 2
cout<<+ +y<<" "; cout<<i<<endl; // Output: 3
+x; x=(--y)+x; cout<<j--<<endl; // Output: 8
output : 5 cout<<--x; cout<<--j<<endl; // Output: 6
output : 9 5 11

43
4. Relational Operators

44
Example:

5 >= 6 false
1.7 < 1.8 true
4 + 2 == 5 false
2 * 4 != 7 true

45
5. Logical Operators
(&&, ||, !)

46
false || false false

47
6.Conditional operator ( ? )
 The conditional operator evaluates an
expression and returns a different value
according to the evaluated expression,
depending on whether it is true or false.
• Syntax is: condition ? result1 : result2

• Example :
• int a=9 , b=3 ,c=4;
• a=(b>a-4)?a++: --c;
• cout<<a; // prints 3 48
7. Comma operator (,)
• used to combine multiple expressions.
• Rule : Evaluate expressions from left to
right and return the value of the right
most expression .
• Example : a=(b=3,b+2) // a=5 and b= 3;

49
Type conversion
• What is Type Conversion
– It is the process of converting one type into
another. In other words converting an
expression of a given type into another is
called type casting.

– There are two ways of achieving the type


conversion, namely:
– Automatic Conversion or Implicit Conversion
– Type casting or Explicit Conversion

50
Automatic Conversion or Implicit Conversion
• This is not done by any conversions or
operators. In other words value gets
automatically converted to the specific
type in which it is assigned.
Example: short x=60;
int y;
y=x;
• In the above example, the data type short
namely variable x is converted to int and is
assigned to the integer variable y.

51
Type casting or Explicit Conversion
• Explicit conversion can be done using type
cast operator and the general syntax for
doing this is:

datatype (expression);
OR
(datatype) expression;

• The datatype is the type of data that you


want your expression to be changed to.
52
#include <iostream>
using namespace std;
int main()
{
int a;
float b,c;
cout<<“Enter the value of a:”;
cin>>a;
cout<<“\n Enter the value of b:”;
cin>>b;
c = float(a)+b;
cout<<”\n The value of c is:”<<c;
return 0;
}
53
Operator precedence table
• defines priority of operation in an expression
Level Operator Description Grouping
1 ()
2 ++ -- Unary (prefix)
! Unary NOT
3 + - Unary sign
4 (type) Type casting Right to left
5 * / % Multiplicative Left to right
6 + - Additive Left to right
7 < > <= >= Relational Left to right
8 == != Equality Left to right
9 && Logical and Left to right
10 || Logical or Left to right
11 ?: Conditional Right to left
12 = *= /= %= += -= Assignment Right to left
13 , comma Left to right

NB: priority level is : Unary--->Type cast--->Arithmetic--->Relational ---


54
>logical --> assignment -->comma.
Example
• Evaluate the following expressions, taking
into consideration operator precedence
• a)4+7*6/3-5 //results in 13
• b)15/3*10-(5+7)/6 //results in 48
15/3*10-12/6=50-2=48

55
Library functions

56
57
58
59
Example 1
 // program that test library functions sin() and sqrt()
#include <iostream>
#include <cmath> /* necessary to use mathematical
functions in library */
#define pi 22.0/7
using namespace std;
void main ()
{
double x= pi/6; // 30 degree = pi/6 in radian
cout<<sin(x)<<endl;
}

60
Example 2

/* Test arithmetic operations (TestArithmetics.cpp) */


#include <iostream>
using namespace std;
int main()
{
int number1, number2; // Declare 2 integer variable number1 and number2
int sum, difference, product, quotient, remainder; // declare 5 int variables
cout << "Enter two integers (separated by space): "; // Prompt user for the two numbers
cin >> number1 >> number2;
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;
cout << "The sum, difference, product, quotient and remainder of "
<< number1 << " and " << number2 << " are "
<< sum << ", "
<< difference << ", "
<< product << ", "
<< quotient << ", and "
<< remainder << endl;
quotient = number1 / number2;
cout << "The new quotient of " << number1 << " and " << number2
<< " is " << quotient << endl;
return 0;
}

You might also like