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

Chapter 3- Fundamentals of C++ programming Languages(4)

Chapter Three covers the fundamentals of C++ programming, including its history, structure, and basic components such as input/output and data types. It explains the evolution of C++ from C, its hybrid nature, and the significance of tokens like keywords and identifiers. The chapter also details the process of compiling and running C++ programs, along with examples of simple code and comments.

Uploaded by

actskebede
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 3- Fundamentals of C++ programming Languages(4)

Chapter Three covers the fundamentals of C++ programming, including its history, structure, and basic components such as input/output and data types. It explains the evolution of C++ from C, its hybrid nature, and the significance of tokens like keywords and identifiers. The chapter also details the process of compiling and running C++ programs, along with examples of simple code and comments.

Uploaded by

actskebede
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Chapter Three

FUNDAMENTALS OF C++
PROGRAMMING LANGUAGES
TOPICS COVERED UNDER THIS CHAPTER
2.1 - A brief history of C++
2.2 - The structure of C++ program
2.3 - Input/output in C++
2.4 - Comments in C++
2.5 - C++ tokens (Keywords, Identifiers, Constants, and Operators)
2.5 Basic data types
2.6 - What is a variable?
2.0 - A BRIEF HISTORY OF C++
• HOME READING !!!
• Computer languages have undergone dramatic evolution since the
first electronic computers were built to assist in telemetry
calculations during World War II.
• Early on, programmers worked with the most primitive computer
instructions: machine language.
• These instructions were represented by long strings of ones and
zeros.
CONT…
• Soon, assemblers were invented to map machine instructions to
human-readable and manageable mnemonics such as ADD and MOV.
• In time, higher-level languages evolved, such as BASIC and
COBOL.
• These languages let people work with something approximating
words and sentences such as Let I = 100.
• These instructions were translated back into machine language by
interpreters and compilers.
CONT…
How C++ evolved
• Bjarne Stroustrup took the most popular language for commercial
software development, C, and extended it to provide the features
needed to facilitate object-oriented programming.
• He created C++, and in less than a decade it has gone from being
used by only a handful of developers at AT&T to being the
programming language of choice for an estimated one million
developers worldwide.
CONT…
How C++ evolved
• It is expected that by the end of the decade, C++ will be the
predominant language for commercial software development.
• While it is true that C++ is a superset of C, and that virtually any
legal C program is a legal C++ program, the leap from C to C++ is
very significant.
• C++ benefited from its relationship to C for many years, as C
programmers could ease into their use of C++.
CONT…
How C++ evolved
• As you may know, C++ was built upon the foundation of C. In fact,
C++ includes the entire C language, and (with minor exceptions) all
C programs are also C++ programs.
• When C++ was invented, the C language was used as the starting
point
What is C++?
C++ is a language used to program computers to perform specific tasks.
C++ Is not purely Object-oriented language, But A hybrid the
functionality of C programming language.
While it is true that C++ is a superset of C, and that virtually any legal
C program is a legal C++ program.
C++ is fun and easy to learn high level programming language.

C++ is used to create computer programs, and one of the most used
language in game development, today's operating systems,…
2.1 - BASIC STRUCTURE OF C++ PROGRAM
Here is our first program:
name of program LAB1.cpp. output
#include<iostream.h> Hello World!
int main()
{
cout<<“Hello World!";
return 0;
}
The left side shows the source code for our first program, which we
can name, for example, LAB1.cpp. The right side shows the result of
the program once compiled and executed.
CONT…
• It is one of the simpler programs that can be written in C++, but it
already includes the basic components that every C++ program has.

We are going to take a look at them one by one:


CONT…
#include<iostream.h>
• Sentences that begin with a pound sign (#) are directives for
preprocessor. It is a header file library that lets us work with input
and output objects, such as cout (used in line 4).
• In this case the sentence #include <iostream.h> tells the compiler's
preprocessor to include the iostream standard header file/ the
declarations of basic standard input-output library in C++, and it is
included because its functionality is used later in the program.
• They are not executable code lines but indications for the compiler.
CONT…
int main ()
• This line corresponds to the beginning of main function declaration.
• The main function is the point by where all C++ programs begin
their execution.
• It is independent of whether it is at the beginning, at the end or in the
middle of the code - its content is always the first to be executed when a
program starts.
• All C++ programs have a main function. main is followed by a pair of
parenthesis () because it is a function.
CONT…
int main ()
• In C++ all functions are followed by a pair of parenthesis () that,
optionally, can include arguments within them.
• The content of main function immediately follows its formal
declaration and enclosed between curly brackets ({}), as in our
example above.
• Blank line. In C++ ignores white space. but we use it to make the
code more readable.
CONT…
cout << "Hello World";
• Cout (pronounced "see-out") is used for output/print text with insertion
operator (<<).
• Cout is standard output stream in C++ (usually the screen), and the full
sentence inserts a sequence of characters (in this case "Hello World")
into this output stream (the screen).
• Cout is declared in the iostream.h header file, so in order to be able to
use it that file must be included.
CONT…
Semicolon character (;)
Every C++ statement ends with a semicolon;
This character signifies the end of the instruction and must be
included after every instruction in any C++ program (one of the most
common errors of C++ programmers is indeed to forget to include a
semicolon ; at the end of each instruction).
CONT…
return 0;
This shows the end of main function.
The return instruction causes the main () function finish and return the code that
the instruction is followed by, in this case 0.
This is most usual way to terminate the program that has not found any errors
during its execution.
Closing curly bracket }
Do not forget to add the closing curly bracket } at the end the main function.
Both open curly brace and close curly brace are required for every function
definition.
CONT…
The program code has been structured in different lines in order to
be more readable, but it is not compulsory to do so. For example,
instead of
int main ()
{
cout << " Hello World ";
return 0;
}
we could have written:
int main () { cout << " Hello World "; return 0; }
CONT…
• In just one line and this would have had exactly the same meaning.
• In C++ the separation between instructions is specified with an
ending semicolon (;) after each one.
• The division of code in different lines serves only to make it more
legible and schematic for humans that may read it.
CONT…
Here is a program with some more instructions:
// my second program in C++ Output
#include <iostream.h> Hello World!
int main () I'm a C++ program
{ I'm the second c++ program
cout << "Hello World! \n";
cout << "I'm a C++ program"<<endl;
cout << "I'm the second c++ program”:
return 0; }

In the above code we used ‘\n’ and ‘endl’ to display strings on new lines.
CONT…
Given below is the additional program written in C++ which when
executed displays the letters “Hello World” on the display unit.
// First C+ + Program -----------------------Comment Line
#include<iostream.h> -----------------------Inclusion of header files
void main ( ) --------- Name of the main function or start of main () function.
{ ------------------------------------------------- Indicates beginning of main ()
cout<< “Hello World”; ------------- Executable output statement.
} ------------------------------------------------- End of main ()
Generally......
• C++ program is a collection of functions.
• The above example contains only one function, main ().
• As usual, execution begins at main ().
• Every c++ program must have a main ().
• The c++ statements terminate with semicolon.
2.2 Process of Compiling and Running programs

1. Editing source code:


 In programming context, writing a program is commonly referred to as editing source
code.
 In this process create C++ program/code using editor like Dev++ and make necessary
corrections as well as save the program using .cpp extensions. e.g my.cpp.
 By following the rules/ syntax of the high-level language.
2. Preprocessing: 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.
Removing comments and blank spaces from the source code before compilation
takes place.
Contt…
3.Compiling:The next step after preprocessing in which the source code is translated into
object code is compiling.
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.

4.Linking
C++ programs contain references to functions defined elsewhere such as libraries.
 Linker combines the object code compiled from your source code with the imported
library functions to produce an executable file.
Linker: a program that combines the object program with other programs in the library
and is used in the program to create executable code.
Contt…
5. Loading
 Before a program is executed, it must be loaded from the disk into main
memory.
 Loader takes executable file from the storage media and loads it into main
memory.
 In this step, load the executable program into main memory for execution,
program called a loader accomplishes this task.

6. Execution or Run: -The final step is to execute the program.


Contt…
2.3 – INPUT(User input) /OUTPUT((Print text) IN C++
 cout is pronounced “C-out". Used for output, and uses the insertion
operator (<<)
 cin is pronounced “C-in". Used for input, and uses the extraction
operator (>>).
#include <iostream.h>
void main ()
{
int a;
cout<<”enter values of a”; // type a number and press enter
cin>>a; // get user input from the keyboard
cout<<”The number is:“<<a; } // display the input value.
CONT…
• In the above program the statement cin>>a; is an input statement
and causes the program to wait for the user to type the numbers.
• The operator >> is known as extraction (or) get from operator.
• The statement cout<<”the number is:”<<a; is an output statement
causes the string in quotation marks to be displayed on the screen as
it is and then the content of the variable a is displayed.
• The operator << is known as insertion (or) put to operator.
2.4 - COMMENTS IN C++
• Single line comment: C++ introduces single line comment // (double
slash). Comments starts with a double slash symbol and terminate at
the end of line.
Example:In above code cout << “enter value of a "; // type a number and press enter

• Multi line comment: Multi line comment symbols are /*, */ the
following comment is allowed,
/* this is an example of C++ program to
illustrate some of its features */
Note :Comment lines in the program are ignored by the compiler.
CONT…
• All the lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behavior of the
program.
• They can be used by the programmer to include short explanations
or observations within the source itself.
• In this case, the line is a brief description of what our program
does.
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.
There is a number of choices in IDEs, so focusing the best C++ IDEs good
practices.
E.g: Visual studio, Code::Blocks, Dev C++, Codelite, Clion, and Eclipse….
2.5 - C++ TOKENS
• C++ instructions are formed using definite symbols and words
according to some rigid rules known as syntax rules.
• Every program instruction must confirm correctly the syntax rules of
the programming language.
• The smallest individual unit of a program written in any language is
called a token(smallest piece of code understood by C++ compiler).
• keywords, identifiers, constants, variables, strings, comments, data
types, expressions, statements, operators ,brackets [ ], braces { }, and
parentheses ( ) are examples of basic elements of c++ programming/
tokens.
CONT…
Keywords
Syntax rules (or grammar) of C++ define certain symbols to have a
unique meaning within a C++ program.
These symbols (reserved words) can't used for any other purposes.
Keywords are pre-defined or reserved words in a programming language.
Each keyword is designed to perform a specific function in a program.
CONT…
Reserved word is a special word in a programming language that
cannot be used as a name.
Programmer cannot usually change the meaning of these words.
Since keywords are referred names for a compiler, they can’t be used
as variable names ,so trying to assign a new meaning to the keyword
which is not allowed.
All reserved words are in lower-case letters.
CONT…
For example, the following expressions are always considered
keywords according to the ANSI-C++ standard.
CONT…
Identifiers
• A valid identifier is a sequence of one or more letters, digits or
underscores symbols.
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.
Valid variable identifiers should always begin with a letter. They can
also begin with an underscore character ( _ ) and can never begin with a
digit.
CONT…
• Neither spaces nor marked letters can not be part of an identifier.
Only letters, digits and underscore characters are valid.
• They cannot match from any keyword of the C++ language.
• Very important: the C++ language is "case sensitive", that means an
identifier written in capital letters is not equivalent to another one
with the same name but written in small letters. For example the
variable result is not the same as the variable RESULT or Result.
CONT…
The rules of naming identifiers in C++:
C++ is case-sensitive so that uppercase letters and lower case letters are different.
Ex Man and man 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.
Keywords cannot be used as identifier.
EXAMPLES..
DATA TYPES
All variables use data-type during declaration, to restrict the type of data to be
stored. i.e. , we can say that data types are used to tell the variables the type of
data it can store in memory.
Whenever a variable is defined in C++, the compiler allocates some memory
spaces for that variable based on the data-type size.
Every data type requires/has a different amount of memory.
Data types in C++ is mainly divided into three types:
1. Primitive / fundamental data types
2. Derived data types
3. Abstract or user-defined data types
CONT…
Primitive data types: This data types are built-in or predefined data
types and can be used directly by the user to declare variables.
Example of basic fundamental data types are:
• Integer: They are the numbers without decimal part. ex: 69, 360, 32330.
• Character: Any letter enclosed within single quotes comes under character.
• Boolean : Used to store one of the two values. True/false
• floating point: They are the numbers with decimal point. ex: 69.65.
• double floating point
• valueless or void
• wide character: Character with 2/4 byte.
CONT….

The modifiers signed, unsigned, long, and short may be applied to character and
integer basic data types. However, the modifier long may also be applied to double.
Derived data types: are derived from the primitive or built-in data types are
referred to as derived data types. These can be four types namely:
• Function, Array, Pointer ,Reference
Abstract or user-defined data types: These data types are defined by user itself,
like, defining a class in C++ or a structure. EX:
• Class ,Structure ,Union ,Enumeration
CONT…
Summarize the basic fundamental data types in C++, as well as the range/size.
CONT…
Operators
• An operator is a symbol that tells the computer to perform certain
mathematical (or) logical manipulations.
• Operators used in programs to manipulate data and variables.
• They include:
1. Arithmetic operators. 5. Increment / decrement operators.

2. Relational operators. 6. Conditional operators


3. Logical operators. 7. Bitwise operators and etc.
4. Assignment operators.
CONT…
Operators
1. Arithmetic operators –
• C++ provides all the basic arithmetic operators like add (+), subtract
(-), Multiply (*), divide (/), and addition to mod (%).
• Modulo is the operation that gives the remainder of a division of two
values.
• mod gives remainder of division.
• Example, for mod: if a = 10; b = 3; c = a % b; c = 1.
CONT…
Operators output
// C++ code for arithmetic Operators 25
#include<iostream.h> 5
void main() 150
1
{
5
int x=15, y=10, a, s, m, d, e;
a = x+y; s = x-y;
cout<<a<<endl<<s;
}
CONT…

2.Relational operators –
• These are operators which relate the operands on either side of them
like less than (<), less than or equal (<=), equal to (==), greater
than (>), greater than or equal (>=) and not equal (! =).
• Used for comparing two or more numerical values.
 == 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.
CONT…

 >= 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.
CONT…
3. Logical operators – They are mainly used in conditional statements and
loops for evaluating a condition.
Like && (Meaning logical and), || (logical or), ! (logical not).
let’s say we have two Boolean variables b1 and b2.
 b1&&b2 will return true if both b1 and b2 are true else false.
 b1||b2 will return false if both b1 and b2 are false else 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.
EXAMPLE
CONT…
4. Assignment operators: used to assign the result of an expression to a
variable and the symbol used is “=“ it is 3 types.
i. Simple assignment------------a = 9;
ii. Multiple assignment----------a = b = c = 6;
iii. Compound assignment------
a + = 15; (equal to a = a +15 ;)
b - = 5; (equal to b = b-5).
c * = 6; (equal to c = c * 6).
d / = 5; (equal to d = d/5;).
e % = 10; (divide e by 10 & store remainder
in e).
CONT…
Operators Output
//c++ code for assignment operators a=11
#include<iostream.h> b=1
int main() c=18
{ d=2
int a=9, b=4, c=6, d=8, e= 10; e=1
a+=2; b-=3; c*=3; d/=4; e%=3;
cout<<"a="<<a<<endl<<"b="<<b<<endl<<"c="<<c<<endl<<"d="<<d
<<endl<<"e="<<e;
}
CONT…
5. Auto increment / decrement (+ + / - -)
• Used to automatically increment and decrement the value of a
variable by 1. There are 2 types.
i. Prefix auto increment / decrement --- adds/subtracts 1 to the
operand & result is assigned to the variable on the left.
CONT…

ii. Postfix auto increment /decrement --- This first assigns the value to
the variable on the left & then increments/decrements the operand.

Generally, a=a+1 can be written as ++a, a++ or a+=1. Similarly a=a-1


can be written as a--, --a or a -= 1.
CONT…
//c++ code for auto increment/decrement operators.
#include<iostream.h>
int main() {
int a=5, b, c, d, e, x=4, z=5, t=6;
b=++a; z=4
cout<<"a="<<a<<endl<<"b="<<b<<endl;
c=x++; t=5
cout<<"x="<<x<<endl<<"c="<<c<<endl;
d=--z;
cout<<"z="<<z<<endl<<"d="<<d<<endl;
e=t--;
cout<<"t="<<t<<endl<<"e="<<e<<endl;
}
CONT…
6. Conditional operator (ternary operator) – ?
• Its format is: condition ? result1 : result2 Or
•If the condition/ exp1 is true the expression will return result1/exp2, if it is
not it will return result2/exp3.
• For example, consider the following statements.
a=10;
b=15;
x = (a>b)? a: b; in this example x will be assigned the value of b.
CONT…
Operators
//c++ code for ternary operator
#include<iostream.h>
void main()
{
float a = 10.5, b = 12.6, x;
x= (a>b)?a:b;
cout<<”x=”<<x;
}
CONT…
Constants
• Constant in C++ refers to fixed values that do not change during the
execution of a program.
• Constant is an expression with a fixed value.
• Constant expressions consist of only constant values.
• Unlike variables, its value can not be changed or modified after their
definition.
In C++ program we can define constants in two ways:

1. Using #define preprocessor directive

2. Using a const keyword.


Example….
CONT…
E.g.2: C++ code for constant variable initialization
// use of a properly initialized constant variable
#include <iostream>
using namespace std; Output
int main() The value of constant variable x is: 7
{
const int x = 7; // initialized constant variable
cout << "The value of constant variable x is: " << x <<
endl;
return 0;
CONT…
E.g. 3: a const variable must be initialized
#include<iostream>
using namespace std;
int main()
{
const int x; // Error: x must be initialized
x = 7; // Error: cannot modify a const variable
return 0;
}
What is a Variable?
• A variable is a data name that may be used to store data value.
• In C++ a variable is a place to store information in memory.
• Programs need a way to store the data they use. Variables offer various
ways to represent and manipulate that data.
• The value of a variable may vary throughout program means that, a
variable may take different values at different times during
execution.
• Each a variable should have its own unique name(identifier) to
indicate the storage area.
CONT…

• A variable is a location(storage area) in your computer's memory in


which you can store a value(info) and from which you can later
retrieve that value.

• When you define a variable in C++, you must tell the compiler what
kind of variable it is: an integer, a character, and soon.

• This declaration tells the compiler how much room to set aside and
what kind of value you want to store in your variable.
CONT…
Declaration of variables
• In order to use a variable in C++, we must first declare it i.e.
specifying the data types and name(the identifier).
Syntax: data type valid variable/ identifier;
•For example:
int a; int c,d,e; float mynumber;
double b_c;

All are valid declarations of variables.


CONT…
Declaration of variables
• If you need to declare several variables of the same type and you want to
save some writing work you can declare all of them in the same line
with commas.
For example:
int a, b, c; declares three variables (a, b and c) of type int and has
exactly the same meaning as if we had written:
int a;
int b;
int c;
SCOPE OF VARIABLE
Scope of variables refers to area of the program where the variables can be accessed
after its declaration.
Inside a function or a block which is called local variables.
Local variables can be used only by statements that are inside that function or
block of code.
In the definition of function parameters which is called formal parameters, and

Global variables are defined outside of all the functions, usually on top of the
program.
It hold their value throughout the lifetime of your program.
It can be accessed by any function.
CONT…
Initialization of variables: done by appending an equal sign
followed by value to which variable will be initialized (known as c-
like): Syntax: data type identifier = initial_value;
For example: int a = 5;
The other way to initialize variables, known as constructor
initialization, is done by enclosing the initial value between
parentheses (()): Syntax: data type identifier (initial_value) ;
For example: int a (5) ;
 Both ways are valid and equivalent in C++.
N D
E

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy