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

Chapter_2-1programming[1]

Chapter 2 covers the basics of C++ programming, including its history, structure of a C++ program, and the compilation process. It explains key concepts such as variables, identifiers, data types, constants, and operators, along with examples. The chapter also discusses the use of Integrated Development Environments (IDEs) and the importance of syntax rules in programming.

Uploaded by

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

Chapter_2-1programming[1]

Chapter 2 covers the basics of C++ programming, including its history, structure of a C++ program, and the compilation process. It explains key concepts such as variables, identifiers, data types, constants, and operators, along with examples. The chapter also discusses the use of Integrated Development Environments (IDEs) and the importance of syntax rules in programming.

Uploaded by

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

Chapter 2: Basics of C++ programming

April 5, 2025
C++ Programming Language
The C++ programming language was developed by Bjarne Stroustrup
at Bell Laboratories in 1971.
Since C++ is an attempt to add object oriented features to C the
developer named it C++.

04/05/2025 Fundaments of Programming 2


Structure of C++ program
#include<iostream>
using namespace std;
int main()
{
cout<<“Hello World!”;
return 0; Program Statements
}

04/05/2025 Fundaments of Programming 3


Structure of C++ program
#include <iostream>
This line is a preprocessing directive.
 # is read as hash.
 It can be considered as NB or remark for it urges the compiler to include (add or import) the file enclosed
under the angle brackets (i.e., the file iostream) from the standard library of C++.
 Keyword include is used to include the external file to our code.
This process is done automatically and is invisible to us.
using namespace std;
The program needs to display a message on the screen, cout, has longer name: std::cout.
This using namespace std directive allows us to omit the std:: prefix and use their shorter names.
The name std stands for “standard”.
The using namespace std line indicates that some of the names we use in our program are part of
the so-called “standard namespace.”

04/05/2025 Fundaments of Programming 4


Structure of C++ program
int main() {
This specifies the real beginning of our program.
Here we are declaring a function named main.
All C++ programs must contain this function to be executable.
The opening curly brace at the end of the line marks the beginning of
the body of a function.
The body of a function contains the statements the function is to
execute.
The main function is the point by where all C++ programs start their
execution, independently of its location within the source code.
04/05/2025 Fundaments of Programming 5
Structure of C++ program
cout << "Hello World!";
This statement executed to print the message Hello World! on the
screen.
A statement is the fundamental unit of execution in a C++ program.
All statements in C++ end with a semicolon (;).

04/05/2025 Fundaments of Programming 6


Structure of C++ program
return 0;
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 0).
A return code of 0 for the main function is generally interpreted as the
program worked as expected without any errors during its execution.
}
The closing curly brace marks the end of the body of a function.
Both the open and close curly brace are required for every function
definition.
04/05/2025 Fundaments of Programming 7
C++ IDEs
IDEs (Integrated Development Environments) is a tools available to
developers.
These tools enhance developer’s workflows, reduce debugging time, and
make them more productive.
IDEs go beyond typical text editors by integrating compiling, code
completion, syntax highlighting, debugging, profiling, and testing and much
more in one comprehensive user interface.
E.g.: Visual studio, Code::blocks, Dev C++, CodeLite, Clion, and Eclipse

04/05/2025 Fundaments of Programming 8


Showing Sample Program
#include<iostream>
using namespace std;
int main()
{
cout<<“This is a simple C++ program!”;
return 0;
}

04/05/2025 Fundaments of Programming 9


Process of compiling and running programs
There are six major types of programming process:
Editing process

Preprocessing

Compiling

Linking

Loading, and

Executing or running

04/05/2025 Fundaments of Programming 10


Process of compiling and running programs
1. Editing: You use a text editor to create a C++ program following the rules, or
syntax, of the high-level language.
This program is called the source code, or source program.
The program must be saved in a text file that has the extension .cpp.
 For example, if you saved the preceding program in the file named lab1, then its
complete name is lab1.cpp.
Source program: A program written in a high-level language.
2. Preprocessing: The C++ program given in the previous slide contains the
statement
#include <iostream>
 In a C++ program, statements that begin with the symbol # are called
preprocessor directives.
These statements are processed by a program called preprocessor.
04/05/2025 Fundaments of Programming 11
Process of compiling and running programs
3. Compiling: After processing preprocessor directives, the next step is to verify
that the program obeys the rules of the programming language
The compiler checks the source program for syntax errors and, if no error is
found, translates the program into the equivalent machine language.
The equivalent machine language program is called an object program.
Object program: The machine language version of the high-level language
program

04/05/2025 Fundaments of Programming 12


Process of compiling and running programs
4. Linking: - The programs that you write in a high-level language are developed
using an integrated development environment (IDE).
The IDE contains many programs that are useful in creating your program.
A program called a linker combines the object program with the programs from
libraries.
 Linker: A program that combines the object program with other programs in
the library and is used in the program to create the executable code.
5. Loading: - You must next load the executable program into main memory for
execution. A program called a loader accomplishes this task.
Loader: A program that loads an executable program into main memory.
6. Execution or run: -The final step is to execute the program.

04/05/2025 Fundaments of Programming 13


Basic elements of programming
 A programming language is designed to process certain kind of data consisting of
numbers, characters and strings and finally provide a useful output.
 The task of processing of data is accomplished by executing a sequence of precise
instructions.
 These instructions are formed using definite symbols and words according to some rigid
rules known as syntax rules.
 C++ programs are built by combining some basic elements in a fashion dictated by the
syntax rules.
 Some of the basic elements of C++ programming are identifiers, variables, literals
(constants), keywords (reserved words), comments, data types, expressions, operators,
and statements.
 These elements are the smallest piece of code that is understood by the C++ compiler
known as tokens.
04/05/2025 Fundaments of Programming 14

Variables
Variables are nothing but reserved memory locations to store values.
 They are containers for storing data values.
 In algebra, variables are used to represent numbers.
 The same is true in C++, except C++ variables also can represent values other than numbers.
#include <iostream>
using namespace std;
int main()
{
int x;
x = 10;
cout << x << endl;
}
 The above code uses X variable to store an integer value and then prints the value of the
variable
04/05/2025 Fundaments of Programming 15
Identifier
The C++ identifier is a name used to identify a variable, function, class, module, or any other
user-defined item.
Identifiers in C++ are names of functions, names of arrays, names of variables, and names of
classes.
The rules of naming identifiers in C++:
 C++ is case-sensitive so that uppercase letters and lower case letters are different.
 Thus, Pc and pc are two different identifiers in C++.
 The name of identifier cannot begin with a digit.
 However, underscore ( _ ) can be used as first character while declaring the identifier.
 Only alphabetic characters, digits and underscore ( _ ) are permitted in C++ language for
declaring identifier.
 Other special characters are not allowed for naming a identifier including space
 Keywords cannot be used as identifier.

04/05/2025 Fundaments of Programming 16


Conti…
 A variable name is one example of an identifier.
 An identifier is a word used to name things.
 One of the things an identifier can name is a variable.

04/05/2025 Fundaments of Programming 17


Examples

04/05/2025 Fundaments of Programming 18


Keywords (Reserved words)
 A reserved word is a special word in a programming language that
cannot be used as a name.
 A programmer cannot usually change the meaning of these words
without losing the original meaning of the word.
 The syntax rules (or grammar) of C++ define certain symbols to have
a unique meaning within a C++ program.
 These symbols, the reserved words, must not be used for any other
purposes.
 All reserved words are in lower-case letters.

04/05/2025 Fundaments of Programming 19


Examples

NB: Keywords are always written or typed in short(lower) cases. In the above
figure some keywords are written in uppercase, they are incorrectly formatted.
04/05/2025
Fundaments of Programming
20
Scope of variable
 A scope is a region of the program

 There are three places, where variables can be declared :-

Inside a function or a block which is called local variables,

In the definition of function parameters which is called formal


parameters, and
Outside of all functions which are called global variables.

04/05/2025 Fundaments of Programming 21


Global Variable
Global variables are defined outside of all the functions, usually on
top of the program.
The global variables will hold their value throughout the lifetime of
your program.
A global variable can be accessed by any function.
That is, a global variable is available for use throughout your entire
program after its declaration.

04/05/2025 Fundaments of Programming 22


Example

04/05/2025 Fundaments of Programming 23


Local variables
 Local variables can be used only by statements that are inside that function or
block of code.

04/05/2025 Fundaments of Programming 24


Data types
All variables use data-type during declaration to restrict the type of data to
be stored.
Therefore, data types are used to tell the variables the type of data it can
store.
Whenever a variable is defined in C++, the compiler allocates some
memory for that variable based on the data-type with which it is declared.
Every data type requires a different amount of memory.

04/05/2025 Fundaments of Programming 25


Data types
Primitive Data Types: These data types are built-in or predefined data
types and can be used directly by the user to declare variables.
Example: int, char , float, bool etc.
Primitive data types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point

04/05/2025 Fundaments of Programming 26


signed and unsigned Modifiers
Signed variables can hold both positive and negative integers
including zero. For example,

Here,
 x holds a positive-valued integer
 y holds a negative-valued integer
 z holds a zero-valued integer
04/05/2025 Fundaments of Programming 27
signed and unsigned Modifiers
The unsigned variables can hold only non-negative integer values. For
example,

Here,
 x holds a positive-valued integer
 y holds zero

04/05/2025 Fundaments of Programming 28


Data types
Next you have a summary of the basic fundamental data types in C++, as well as the
range of values that can be represented with each one:

04/05/2025 Fundaments of Programming 29


Variable declaration
 In order to use a variable in C++, we must first declare it specifying
which data type we want it to be.
 The syntax to declare a new variable is to write the specifier of the
desired data type (like int, bool, float...) followed by a valid variable
identifier.
data_type variable_list ;
 Here, data_type must be a valid C++ data type including char, int, float,
double, bool or any user-defined object, etc., and variable_list may
consist of one or more identifier names separated by commas.
Example:

04/05/2025 Fundaments of Programming 30


Initialization of variables
When declaring a regular local variable, its value is by default undetermined.
But if you want to determine when you declare, you can initialize the variable.
There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the
value to which the variable will be initialized:
type identifier = initial_value ;
For example: int a = 0 ;
The other way to initialize variables, known as constructor initialization, is done by
enclosing the initial value between parentheses (()):
type identifier (initial_value) ;
For example: int a (0) ;

04/05/2025 Fundaments of Programming 31


Constants
As the name suggests the name constants are given to such variables or
values in C++ programming language which cannot be modified once
they are defined.
They are fixed values in a program.

In C++ program we can define constants in two ways as shown below:

1. Using #define preprocessor directive

2. Using a const keyword


04/05/2025 Fundaments of Programming 32
Defining Constants
1. Using #define preprocessor directive: This directive is used to declare
an alias name for existing variable or any value. We can use this to
declare a constant as shown below:
#define identifierName value
identifierName: It is the name given to constant.
value: This refers to any value assigned to identifierName.
2. using a const keyword: Using const keyword to define constants is as
simple as defining variables, the difference is you will have to precede
the definition with a const keyword.

04/05/2025 Fundaments of Programming 33


The #define Preprocessor
Following is the form to use #define preprocessor to define a constant

04/05/2025 Fundaments of Programming 34


The const Keyword

04/05/2025 Fundaments of Programming 35


Operators
 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
 In C++ basic operators are the following:
Arithmetic Operators
Increase and Decrease Operators
Assignment Operators
Logical Operators
Relational Operators
Conditional Operator

04/05/2025 Fundaments of Programming 36


Arithmetic operators
 The five arithmetical operations supported by the C++ language are:

Symbols Descriptions
+ addition
- subtraction
* multiplication
/ division
% modulo

 Operations of addition, subtraction, multiplication and division literally correspond


with their respective mathematical operators.
 The only one that you might not be so used to see is modulo; whose operator is the
percentage sign (%).
04/05/2025
Modulo is the operation that gives the remainder
Fundaments of Programmingof a division of two values. 37
Increment and decrement (++, --)
 The increment operator (++) and the decrement operator (--) increase or
reduce by one the value stored in a variable.
 They are equivalent to +=1 and to -=1, respectively. Thus:

c++;

c+=1;

c=c+1;

are all equivalent in its functionality: the three of them increase by one the
value of c.
04/05/2025 Fundaments of Programming 38
Exmaple

04/05/2025 Fundaments of Programming 39


Example
#include <iostream>
using namespace std;
int main()
{
int a=21;
int c;
c=a++;
cout<<c<<endl;
cout<<a;
return 0;
}
Result
21
22

04/05/2025 Fundaments of Programming 40


Example

04/05/2025 Fundaments of Programming 41


Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, and %=
 num2 = num1 would assign value of variable num1 to the variable.

 num2+=num1 is equal to num2 = num2 + num1

 num2-=num1 is equal to num2 = num2 - num1

 num2*=num1 is equal to num2 = num2 * num1

 num2/=num1 is equal to num2 = num2 / num1

 num2%=num1 is equal to num2 = num2 % num1


04/05/2025 Fundaments of Programming 42
Example

04/05/2025 Fundaments of Programming 43


Logical Operators
Logical Operators are used with binary variables.
They are mainly used in conditional statements and loops for evaluating a
condition.
Logical operators in C++ are: &&, ||, and !
Let’s say we have two Boolean variables b1 and b2.
 b1&&b2 will return true if both b1 and b2 are true else it would return
false.
 b1||b2 will return false if both b1 and b2 are false else it would return true.
 !b1 would return the opposite of b1, that means it would be true if b1 is
false and it would return false if b1 is true.

04/05/2025 Fundaments of Programming 44


Logical Operators Example

04/05/2025 Fundaments of Programming 45


Relational operators
In C++, Relational Operators are used for comparing two or more
numerical values.
We have six relational operators in C++: ==, !=, >, <, >=, and <=
 == returns true if both the left side and right side are equal
 != returns true if left side is not equal to the right side of operator.
 > returns true if left side is greater than right.
 < returns true if left side is less than right side.
 >= returns true if left side is greater than or equal to right side.
 <= returns true if left side is less than or equal to right side.

04/05/2025 Fundaments of Programming 46


Relational operators Example

04/05/2025 Fundaments of Programming 47


Conditional operator ( ? )
 The conditional operator evaluates an expression returning a value if
that expression is true and a different one if the expression is evaluated
as false.
 Its format is: condition ? result1 : result2
If condition is true the expression will return result1, if it is not it
will return result2.

04/05/2025 Fundaments of Programming 48


Comment
Program comments are explanatory statements that you can include in the C++
code.
These comments help anyone reading the source code.
All programming languages allow for some form of comments.
C++ supports single-line and multi-line comments.
All characters available inside any comment are ignored by C++ compiler.
C++ comments start with /* and end with */

04/05/2025 Fundaments of Programming 49


Comment
A comment can also start with //, extending to the end of the line

04/05/2025 Fundaments of Programming 50


Basic Input / Output in C++
 In C++ input and output are performed in the form of a sequence of bytes
or more commonly known as streams.
 Input Stream: If the direction of flow of bytes is from the device(for
example, Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from
main memory to device( display screen ) then this process is called output.
 The two instances cout in C++ and cin in C++ of iostream class
 These two are the most basic methods of taking input and printing output
in C++.
 To use cin and cout in C++ one must include the header file iostream in
the program.
04/05/2025 Fundaments of Programming 51

You might also like