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

Unit 2 C++ Programming Basics

This document provides an overview of C++ programming basics, including its history, integrated development environments (IDEs), and fundamental programming constructs. It covers topics such as data types, variables, constants, operators, and input/output statements, along with examples of C++ syntax. The document also explains the role of translators in converting source code and includes details on comments and escape sequences.

Uploaded by

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

Unit 2 C++ Programming Basics

This document provides an overview of C++ programming basics, including its history, integrated development environments (IDEs), and fundamental programming constructs. It covers topics such as data types, variables, constants, operators, and input/output statements, along with examples of C++ syntax. The document also explains the role of translators in converting source code and includes details on comments and escape sequences.

Uploaded by

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

UNIT 2 C++ Programming Basics

Course Learning Outcomes


[CLO1→C2]: Introduction to C++ and IDEs, C++ basic program construct, variables and constants
[CLO2→C2]: Operators and its types, precedence of operators
[CLO3→C2]: Expression and its types

Introduction to C++
Danish computer scientist Bjarne Stroustrup began developing C++ at Bell Laboratories in
1979. It was named C++ in 1983. The first book of C++ programming language was published
in 1985 and it was commercially available.

1. C++ is one of the most popular programming language. It is used all around the
world for developing applications, browsers, video games, etc. Most of the operating
systems including Windows, Mac OS and Linux are built in C++.
2. It is a superset of C. The main difference between C and C++ is that C++ supports
object-oriented programming.
3. It is an intermediate level language, meaning it has features of both high level
language and low-level language for programming of computer hardware.
4. It is easy to learn and use. It is close to C# and Java.

Integrated Development Environment


Integrated Development Environment (IDE) is computer software that brings all the
processes and tools required for program development into one place. It makes all the tasks
needed for building applications into one environment. Most of the new programming
languages use IDE. Today’s modern IDEs have user-friendly Graphical User Interface.

IDEs improve the programmer’s productivity by boosting the speed of program


development tasks. Tools of IDEs help the programmer prevent mistakes.

Prior to IDEs, programmers wrote their programs using text editors. They wrote and saved
an application in the text editor before running the compiler. If errors were found, they had
to go back to the text editor to revise the code.

Translators
A translator is a program that converts source code into machine code. A program written in
a high level language or assembly language is called source code. There are three types of
translators; compilers, interpreters and assemblers.

M. Sajjad Heder Pg. 1


 Compiler
It is a software that translates the entire program written in a high level language
into machine language before execution by the computer CPU. Most of the high
level languages use compilers.
 Interpreter
It is a software that translates high level language program into machine language
one instruction at a time and immediately executes it before translating the next
instruction. It translates the code into machine language and executes it line by line.
 Assembler
It is a software that translates assembly language program into machine language for
execution by the computer CPU.

C++ Basic Program Construct


The following program demonstrates the C++ basic program construct.

#include <iostream>
using namespace std;
int main()
{
int a, b, sum;
cout<<”This is my first C++ program.\n”;
cout<<”Enter the value of a:”;
cin>>a;
cout<<”Enter the value of b:”;
cin>>b;
sum=a+b;
cout<<”Sum of 2 numbers=”<<sum<<endl;
return 0;
}

This program has only one function called main(). The parentheses follow the function
name. Without the parenthesis the compiler would think that it is a variable name. A
program may consist of many functions but on startup, the control always goes to main().
All the programs must have this function.
The word int before the function name indicates that this function has a return value of type
int. This and return statement will be discussed later.
The body of a function is surrounded by braces (curly brackets). In this program there are 9
statements in the function body. All of these end with semicolon (;)
Input/Output Statements
The cout Statement
It is used to output text or values on the screen. The << is called insertion or put to
operator.

M. Sajjad Heder Pg. 2


Syntax
cout<<character string/variable;
This is demonstrated with the following statement in the program.
cout<<”This is my first C++ program.\n”;

The ‘\n’ character at the end of the string constant is an example of escape sequence. It
causes the next output to be displayed on a new line. The endl manipulator used at the end
of the last output statement has the same effect as ‘\n’ escape sequence.
The following program demonstrates the use of ‘\n’ and endl manipulator.
#include<iostream>
using namespace std;
int main()
{
cout<<”\nI am a student.”<<endl;
cout<<”I live in Islamabad.”;
}
The output of the program will be:
I am a student.
I live in Islamabad.
The following single statements can also be used to get the same output.
cout<<”\nI am a student.”<<endl<<”I live in Islamabad.”;
cout<<”\nI am a student.\nI live in Islamabad.”;
cout<<”\nI am a student.”<<”\n”<<”I live in Islamabad”;
The cin Statement
It is used to input data from the keyboard and assign it to one or more variables. The >> is
called extraction or get from operator.
Syntax
cin>>variable;
This is demonstrated with the following statement in the program.
cin>>a;
To assign three values to variables a, b and c. The statement would be:
cin>>a>>b>>c;
The data should be separated with space while entering from the keyboard.

M. Sajjad Heder Pg. 3


Directives
The two lines at the beginning of the program are directives. The first is a preprocessor
directive and the second is a using directive.
Preprocessor Directives
The #include <iostream> is not a program statement. It is not part of function body and
does not end with semicolon, as program statements must. It starts with # (number sign). It
is called a preprocessor directive. It is an instruction to the compiler. The preprocessor
directive tells the compiler to insert the iostream file into the program. There are many
preprocessor directives in C++. Some of these will be explained later. The first line of the
program tells the compiler to add the iostream file to the program before compiling. The
iostream is an example of header file. It is concerned with basic input/output operations. It
is needed by the cout and cin identifiers and << and >> operators used in the program.
The using Directive
The directive:
using namespace std;
says that all the program statements that follow are within the std namespace.

Comments
Comments are explanatory statements that help the reader in understanding the source
code. Comments can be entered at any location in the program. Comments are ignored
during program execution. There are two types of comments in C++. These are single-line
comments and multiple-line comments.
Single-line comments (//)
The single-line comments start with // and continue till the end of the line as demonstrated
in the following program.
// This program displays a message on the screen.
// It displays the message “Hello World” on the screen.
#include <iostream>
using namespace std;
int main()
{
cout<<”Hello World!”; // It prints a message on the screen.
}
Multiple-line Comments (/* and */)
It is used for entering multiple line comments in a program. The /* is used at the beginning
of the comments and */ at the end.

M. Sajjad Heder Pg. 4


/* The following program displays
the message “Hello World!”
on the screen*/
#include <iostream>
using namespace std;
int main()
{
cout<<”Hello World!”; // It prints a message on the screen.
}
Character Set
Character set is a combination of the alphabets, white spaces and some symbols from the
mathematics including the digits and the special symbols. C++ character set means the characters,
digits and the symbols that are understandable and acceptable by the C++ Program.

Constants
In computer programming, a constant is a value that does not change during program
execution. It can be a number, a character or a character string. Some examples of
constants are 17, 8.25, ‘b’ and “Information Technology”. A single character constant is
written within single quotes and a string constant within double quotes.
Variables
A variable is a name of memory location where computer stores values of different data
types. The data stored in a variable may change during program execution.
Rules for Specifying Variable Names
i. Must start with an alphabet or underscore (_)
ii. The following characters are allowed in a variable name
a. Upper-case letters (A to Z)
b. Lower-case letters (a to z)
c. Digits (0 to 9)
d. Underscore
e. Upper-case letter is different from a lower-case letter. For example, the
variable avg is different from AVG and Avg.
iii. Blank space, comma or special symbols such as &, %, $, etc. are not allowed.
iv. Reserved word such as do, while, if, then, etc. have special meaning in C++.
Therefore, these cannot be used as variable names.

M. Sajjad Heder Pg. 5


Data Types in C++

The data types used in C++ are integer, floating-point and character.

Integer

It is a data type used to defines numeric variables to store whole numbers such as 233, -15,
3890, etc. Numbers having fractional part, such as, 2.67 cannot be stored in an integer
variable.

The following table shows the integer types, the number of bytes in takes in memory to
store the value and the range of numbers it can store. It is for 32-bit word.

Integer Type No. of Bytes Range of Numbers


int 4 -2147483648 to 2147483647
Unsigned int 4 0 to 4294967295
Short int 2 -32768 to 32767
Unsigned Short Int 2 0 to 65535
Long Int 4 -2147483648 to 2147483647
Unsigned Long Int 4 0 to 4294967295

The statement:
int a, b, c=10, sum;
declares three variables a, b, c and sum as integer variables and initializes the value of c to
10.
Floating-point
It is a data type used to define variables that can store numbers that have fractional part
such as 4.38, 23.2, -7.99, etc. Floating-point numbers are also called real numbers.

The following table shows the floating-point types, the number of bytes it takes in memory
to store the value and the range of real numbers it can store.

Float Type No. of Bytes Range of Numbers


float 4 -3.4-38 to 3.438 (with 6 digits of precision)
double 8 -1.7-308 to 1.7308 (with 15 digits of precision)

The statement:
float x, y, weight=63.28;
declares three variables x, y and weight as floating-point variables and initializes the variable
weight to 63.28.

M. Sajjad Heder Pg. 6


Character

It is a data type used to define variables that can store only a single character such as ‘a’,
‘&’, ‘%’, etc. Characters are written within single quotation marks. One byte of memory is
set aside in memory to store a single character.

The statement:
char ch1, ch2=’a’;
declares two variables ch1 and ch2 and initializes ch2 to ‘a’.

Escape Sequences

An escape sequences are used inside the cout statement. It begins with a backslash followed
by a character such as ‘\n’, ‘\t’, ‘\r’, etc. Escape sequence are special characters used to
control the output look on screen or printer.

Commonly used escape sequences are \a, \n, \t, \r, \\, \’ \” and \f.

Escape sequence Meaning

\a Produces beep sound


\n Moves cursor to the beginning of next line
\t Moves cursor to the next tabular position
\r Used for Return character
\\ Produces \
\’ Produces single quote
\” Produces double quote
\f Used for form feed

Arithmetic Operators
The arithmetic operators +, -, * and / for addition, subtraction, multiplication and division
work on both integers and floating-point. They are used much the same way as in algebra.
The Remainder Operator (%)
It works only with integers. The remainder operator is represented by the percent symbol
(%). It finds the remainder when one number is divided by another.
6 % 8 will return 6
7 % 8 will return 7
8 % 8 will return 0
9 % 8 will return 1
10 % 8 will return 2
19 % 5 will return 4

M. Sajjad Heder Pg. 7


Arithmetic Assignment Operators
The “=” sign is called assignment operator.
Assignment Statement
The assignment operator is used in an assignment statement. The assignment statement
has the general form:
variable = expression;
Arithmetic Expression
An arithmetic expression is a combination of constants, variables and operators. When an
assignment statement is executed, the expression evaluates to a value which is assigned to
the variable on the left side of “=” sign.
For example,
t = (a + b)*5 – c;
In the above statement, +, -, * are operators, 5 is a constant and a, b and c are variables.
When this statement is executed, it will evaluate to a value which will be assigned to the
variable t.
Total = Total + Item; // Adds item to total
C++ offers a condensed approach which combines an arithmetic operator and an
assignment operator and eliminates the repeated operand.
a += 10; // same as a = a + 10;
a -= 7; // same as a = a - 7;
a *= 2; // same as a = a * 2;
a /= 3; // same as a = a / 3;
a %= 3; // same as a = a % 3;

Increment Operators (++)


You often need to add 1 to the value of an existing variable. You can do it in the normal way:
count = count + 1; // adds 1 to count
Or you can use an arithmetic assignment operator:
count += 1; // adds 1 to count
There is an even more condensed way:
++count; // adds 1 to count

M. Sajjad Heder Pg. 8


Prefix and Postfix
The increment operator can be used in two ways, as prefix, meaning that the operator
precedes the variable and as postfix, meaning that the operator follows the variable.
The following program demonstrate the use of prefix and postfix increment operators.
#include <iostream>
using namespace std;
int main()
{
int count = 10;
cout << “Count=” << count << endl; // displays 10
cout << “Count=” << ++count << endl; // displays 11 (prefix)
cout << “Count=” << count << endl; // displays 11
cout << “Count=” << count++ << endl; // displays 11 (postfix)
cout << “Count=” << count << endl; // displays 12
return 0;
}
Here is the output of the program:
count = 10
count = 11
count = 11
count = 11
count = 12
Decrement Operator (--)
The decrement operator, --, works the same way as increment operator, except that it
subtracts 1 from its operand. It too can be used in both prefix and postfix forms.
Type Conversion
Consider the following program.
#include <iostream>
using namespace std;
int main()
{
int count = 7;
float avgweight = 155.5;
float totalweight = count * avgweight;

M. Sajjad Heder Pg. 9


cout <<”Total Weight = “<<totalweight <<endl;
return 0;
}
In this program, integer variable count is multiplied with float type variable. This is allowed
in C++. The integer variable will be converted to type float and stored in a temporary
variable before being multiplied by the float variable avgweight. C++ automatically does
what you want.
When two operands of different types are in the same expression, the lower-type variable is
converted to the type of the higher-type variable. Types are considered higher or lower
based on the order shown below.
Data Type Order
double Highest
float
long
int
short
char Lowest

M. Sajjad Heder Pg. 10

You might also like