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

Chapter 2 Comp Programming

Uploaded by

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

Chapter 2 Comp Programming

Uploaded by

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

Computer Programming

Chapter 2
Introduction to C++ Programming
1. Basic concepts of C++ programming
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell
Labs. Communicating with a computer involves speaking the language the computer understands. As
the classical method of learning English is to first learn the alphabets used in the language, then learn
to combine these alphabets to form words, which in turn are combined to form sentences and
sentences are combined to form paragraphs. Learning C++ is similar and easier. Instead of
straight-away learning how to write programs, we must first know what alphabets, numbers and
special symbols are used in C++, then how using them constants, variables and keywords are
constructed, and finally how are these combined to form an instruction. A group of instructions
would be combined later on to form a program.

The structure of C++ Programs


A C++ program has the following structure;
1. Preprocessor directives: Programs in C++ are usually started with preprocessor directives.
It instruct the computer to do something, preprocessors directives are instructions to the compiler
telling it to do some tasks.
e.g. #include<iostream>
#-pound sign: This character is a signal to the preprocessor. Each time you start your compiler, the
preprocessor runs through the program and looks for the pound (#) symbols and act on those lines
before the compiler runs.
include: is a preprocessor instruction that directs the compiler to include a copy of the file specified
in the angle brackets in the source code.
2. Main function
The main function tells the compiler where to start the execution of the program. All the statements
that are to be executed are written in the main function. When the program starts, main() is called
automatically. Every C++ program must have one and only one main()function.
Example: int main()
3. variable declaration
Example: int x;
4. Comments
Helps to explain our work in brief for the users
Example: //this is … or /* this is ….*/
Comments can be put in any place as the programmer need
5. Input statement
Used to insert data to the computer from the keyboard. To take input from the keyboard, write the
word cin, followed by the input redirection operator (>>) and the object name to hold the input value.
Example: cin>>x;

1|Page
Computer Programming

6. Output
Used to display the result from the screen. To print a value to the screen, write the word cout,
followed by the insertion operator also called output redirection operator (<<) and the object to be
printed on the screen.
Example: cout<<―sum of two numbers are‖;
7. End statement
return 0;

To understand the basic parts of a simple program in C++, let us have a look at the following code:
Example: look the ff sample programs
#include<iostream>//directive
using namespace std;// Namespace
int main()//main fu/n
{
int x,y,sum;//variable declaration
cout<<―Enter Two Numbers‖<<endl;//output
cin>>x>>y;//input
sum=x+y;//adding two nos
cout<<―sum is‖<<sum;//output
return 0;//end
}

 Any C++ program file should be saved with file name extension ― .CPP ‖
 The first character is the #. This character is a signal to the preprocessor. Each time you start
your compiler, the preprocessor runs through the program and looks for the pound (#)
symbols and act on those lines before the compiler runs.
 The include instruction is a preprocessor instruction that directs the compiler to include a
copy of the file specified in the angle brackets in the source code.
 If the path of the file is not specified, the preprocessor looks for the file under c:\tc\include\
std;folder or in include folder of the location where the editor is stored.
 The effects of line 1, i.e. include<iostream> is to include the file iostream into the program as
if the programmer had actually typed it.
 The main function can be made to return a value to the operating system.
 The Left French brace or ―{―signals the beginning of the main function body and the
corresponding Right French Brace ―}‖ signals the end of the main function body. Every Left
French Brace needs to have a corresponding Right French Brace.
 The lines we find between the braces are statements or said to be the body of the function.
 A statement is a computation step which may produce a value or interact with input and
output streams.
 The end of a single statement ends with semicolon (;).
 Standard end line (endl): The endl is a predefined object of ostream class. It is used to insert a
new line characters and flushes the stream.

2|Page
Computer Programming

2. The Compilation Process


A program goes from text files(or source files) to processor instructions as follows:

Object files are intermediate files that represent an incomplete copy of the program: each source file
only expresses a piece of the program, so when it is compiled into an object file, the object file has
some markers indicating which missing pieces it depends on. The linker takes those object files and
the compiled libraries of predefined code that they rely on, fills in all the gaps, and spits out the final
program, which can then be run by the operating system(OS).
C++ actually adds an extra step to the compilation process: the code is run through a preprocessor,
which applies some modifications to the source code, before being fed to the compiler. Thus, the
modified diagram is:

3. Syntax and Semantics


A programming language is a set of rules, symbols, and special worlds used to construct a program.
In, particular, there are rules of for both syntax and semantics.
Syntax is a formal set of rules that defines exactly which combinations of letters, numbers, and
symbols can be used in a programming language. Syntax rules are the blueprints we use to build
instruction in a program. They allow us to take the elements of a programming language – the basic
building blocks of the language – and assemble them into constructs, which are syntactically correct
structures. If our program not follows any of the rules of the language, the program is said to have
syntax errors and cannot compiled correctly until we fix them.

4. Constants, Variables and Keywords


The alphabets, numbers and special symbols when properly combined form constants, variables and
keywords. A constant is an entity that doesn‘t change whereas a variable is an entity that may change.
. Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new value
5 to the same memory location x. This would overwrite the earlier value 3, since a memory location
can hold only one value at a time. This is shown in Figure

3|Page
Computer Programming

Since the location whose name is x can hold different values at different times x is known as a
variable. As against this, 3 or 5 do not change, hence are known as constants.

Each variable in C++ has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable. The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters
are distinct because C++ is case-sensitive. All variables have three important components:

 Data Type: a type which is established when the variable is defined. (e.g. integer,
real, character etc). Data type describes the property of the data and the size of the
reserved memory.
 Name: a name which will be used to refer to the value in the variable. A unique
identifier for the reserved memory location
 Value: a value which can be changed by assigning a new value to the variable.

Constants
A constant is any expression that has a fixed value. Like variables, constants are data storage
locations in the computer memory. But, constants, unlike variables their content cannot be changed
after the declaration. Constants must be initialized when they are created by the program, and the
programmer can‘t assign a new value to a constant later.
Types of C++ Constants
C++ constants can be divided into two major categories:

Rules for Constructing Integer Constants


a) An Integer constant must have at least one digit.
b) It must not have a decimal point
c) It can be either positive or negative
d) If no sign precedes an integer constant it is assumed to be positive
e) No commas or blanks are allowed within an integer constant
f) The allowable range for integer constants is -32768 to 32767

Ex.: 426, +782, -8000 and -7605

Rules for Constructing Real Constants


Real constants are often called Floating Point constants. The real constants could be written in two
forms—Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional
form:
a) A real constant must be at least one digit.
b) It must have a decimal point

4|Page
Computer Programming

c) It could be either positive or negative


d) Default sign is positive
e) No commas or blanks are allowed within a real constant.

Ex.: +325.34, 426.0, -32.76


Rules for Constructing Character Constants
a) A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single inverted commas.
b) The maximum length of a character constant can be 1 character.

Ex.: 'A', 'I','5' and '='

Rules for Constructing Variable Names


a) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some
compilers allow variable names whose length could be up to 247 characters. Still, it would be
safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as
it adds to your typing effort.
b) The first character in the variable name must be an alphabet or underscore.
c) No commas or blanks are allowed within a variable name.
d) No special symbol other than an underscore (as in gross_sal) can be used in a variable name.

Ex.: num_val (Valid variable name)


m_hra (Valid variable name)
pop@89 (invalid variable name)

C++ Keywords
Keywords are the words whose meaning has already been explained to the C++ compiler (or in a
broad sense to the computer). The keywords cannot be used as variable names because if we do so
we are trying to assign a new meaning to the keyword, which is not allowed by the computer. The
keywords are also called ‗Reserved words‘. There are only 32 keywords available in C++. The
following table gives a list of these keywords.

auto double int struct


break else long switch
case enum Register typedef
char extern Return union
const float Short unsigned
continue for Signed void
default goto Sizeof volatile
do if Static while

5. Data Types
While writing program in any language, we need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means that
when we create a variable we reserve some space in memory. We may like to store information of
various data types like character, integer, floating point, double floating point, boolean etc. Based on
the data type of a variable, the operating system allocates memory and decides what can be stored in
the reserved memory.

5|Page
Computer Programming

C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following
table lists down seven basic C++ data types –

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Syntax and Example for Variable Declaration


A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type, and contains a list of one or more variables.

Syntax: type variable_list;


Examples: int i, j, k;
char c, ch;
float f, salary;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of
an equal sign followed by a constant expression as follows −
type variable_name = value;

Some examples are –


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized
with NULL (all bytes have the value 0); the initial value of all other variables is undefined.
Programming Example:
#include <iostream>
using namespace std;
int main ( )
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;

6|Page
Computer Programming

cout << c << endl ;


f = 70.0/3.0;
cout << f << endl ;
return 0;
}

6. Statements and Expressions


C++ Programs are made up of statements, which are commands that end with a semicolon (;).
Statements are fragments of the C++ program that are executed in sequence.
C++ expression consists of operators, constants, and variables which are arranged according to the
rules of the language. It can also contain function calls which return values.
An expression can consist of one or more operands, zero or more operators to compute a value. Every
expression produces some value which is assigned to the variable with the help of an assignment
operator. Any of the expressions followed by a semicolon is a statement.
Several statements can be grouped together as a compound statement, which begins with an open
brace and then close with a closing brace.
There are basically three types of instructions in C++:
a) Type Declaration Instruction: To declare the type of variables used in a program.
b) Arithmetic Instruction: To perform arithmetic operations between constants and variables.
c) Input Output Instruction: To receive input to variables and produce output.
d) Control Instruction: To control the sequence of execution of various statements in the
Program.

7. Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators

Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example


A= 10, B=20

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give 0

7|Page
Computer Programming

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example


A= 10,
B=20

== Checks if the values of two operands are equal or not, if yes then (A == B) is
condition becomes true. not true.

!= Checks if the values of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value of right (A > B) is
operand, if yes then condition becomes true. not true.

< Checks if the value of left operand is less than the value of right (A < B) is
operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to the value (A >= B) is
of right operand, if yes then condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true.

Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then –

Operator Description Example


A= 1, B=0

&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is


then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B)
operand. If a condition is true, then Logical NOT operator will make is true.
false.

8|Page
Computer Programming

Assignment Operators
There are following assignment operators supported by C++ language −

Operator Description Example

= Simple assignment operator, Assigns values from right side C = A + B will


operands to left side operand. assign value of A +
B into C

+= Add AND assignment operator, It adds right operand to the C += A is equivalent


left operand and assign the result to left operand. to C = C + A

-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent


from the left operand and assign the result to left operand. to C = C - A

*= Multiply AND assignment operator, It multiplies right


C *= A is equivalent
operand with the left operand and assign the result to left
to C = C * A
operand.

/= Divide AND assignment operator, It divides left operand C /= A is equivalent


with the right operand and assign the result to left operand. to C = C / A

%= Modulus AND assignment operator, It takes modulus using C %= A is


two operands and assign the result to left operand. equivalent to C = C
%A

Prefix and Postfix:


 The prefix type is written before the variable. Eg (++ myAge), whereas the postfix type
appears after the variable name (myAge ++).
 Prefix and postfix operators cannot be used at once on a single variable: Eg: ++age-- or --
age++ or ++age++ or - - age - - is invalid
 In a simple statement, either type may be used. But in complex statements, there will be a
difference.
 The prefix operator is evaluated before the assignment, and the postfix operator is evaluated
after the assignment. E.g.
int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
(auto increment postfix) y= k++ + 10; //gives 15 for y
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y
Operator Precedence
 The order in which operators are evaluated in an expression is significant and is determined
by precedence rules. Operators in higher levels take precedence over operators in lower
levels.

9|Page
Computer Programming

Precedence Table: Operators Order


Level
Highest ++ -- (post fix) Right to left
sizeof() ++ -- (prefix) Right to left
*/% Left to right
+- Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Left to right
= ,+=, -=, *=, /=,^= ,%=, &= ,|= ,<<= ,>>= Right to left
Highest , Left to right

E.g.
a==b+c*d
c * d is evaluated first because * has a higher precedence than + and = =.
The result is then added to b because + has a higher precedence than = =
And then == is evaluated.
 Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
 Operators with the same precedence level are evaluated in the order specified by the column
on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated followed by a = b.

8. Errors and Debugging in C++


Error is an illegal operation performed by the user which results in abnormal working of the
program.
Programming errors often remain undetected until the program is compiled or executed. Some of
the errors inhibit the program from getting compiled or executed. Thus errors should be removed
before compiling and executing.
The most common errors can be broadly classified as follows.
1. Syntax errors
2. Run-time Errors
3. Linker Errors
4. Logical Errors
5. Semantic errors

Syntax errors: Errors that occur when you violate the rules of writing C++ syntax are known as
syntax errors. This compiler error indicates something that must be fixed before the code can be
compiled. All these errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it

10 | P a g e
Computer Programming

 Syntax of a basic construct is written wrong.


 Missing semicolon like this:
// C program to illustrate syntax error
#include<iostream.h>
void main()
{
int x = 10;
int y = 15;
cout << x << ―,‖ << y // semicolon missed
// Missing Parenthesis }

Run-time Errors: Errors which occur during program execution(run-time) after successful
compilation are called run-time errors. One of the most common run-time error is division by zero
also known as Division error. These types of error are hard to find as the compiler doesn‘t point to
the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate run-time error
#include<iostream.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
cout<< "resut = "<< div;
}
In the given example, there is Division by zero error. This is an example of run-time error i.e errors
occurring while running the program.

Linker Errors: These errors occur when after compilation we link the different object files with
main‘s object using Ctrl+F9 key (RUN). These are errors generated when the executable of the
program cannot be generated. This may be due to wrong function prototyping, incorrect header
files. One of the most common linker error is writing Main() instead of main().
#include<iostream.h>
int Main() // Here Main() should be main()
{
int a = 10;
cout<< a;
return 0;
}

Logical Errors: On compilation and execution of a program, desired output is not obtained when
certain input values are given. These types of errors which provide incorrect output but appears to
be error free are called logical errors. These are one of the most common errors done by beginners
of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.

11 | P a g e
Computer Programming

// C program to illustrate logical error


int main()
{
int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{
cout<< "loop ";
continue;
}
getchar();
return 0;
}

Semantic errors: This error occurs when the statements written in the program are not meaningful
to the compiler.
// C++ program to illustrate semantic error
int main()
{
int a, b, c;
a + b = c; //semantic error
return 0;
}

Debugging
Debugging is a methodical process of finding and reducing the number of bugs (or defects) in a
computer program, thus making it behave as originally expected.

Some Programming Examples


Example1: Print Number Entered by User
#include <iostream>
using namespace std;
int main()
{ When user enters an integer, it is
int number; stored in variable number using cin.
cout << "Enter an integer: "; Then it is displayed in the screen using
cin >> number; cout.1.
cout << "You entered " << number;
return 0;
}

Output
Enter an integer: 23
You entered 23
This program asks user to enter a number.

12 | P a g e
Computer Programming

Example 2: Swap Numbers (Using Temporary Variable)


#include <iostream>
using namespace std;
int main()
{ To perform swapping in above
int a = 5, b = 10, temp; example, three variables are used.
cout << "Before swapping." << endl; The contents of the first variable
cout << "a = " << a << ", b = " << b << endl; is copied into the temp variable.
temp = a; Then, the contents of second
a = b; variable is copied to the first
b = temp; variable.
cout << "\nAfter swapping." << endl; Finally, the content of the temp
cout << "a = " << a << ", b = " << b << endl; variable is copied back to the
return 0; second variable which completes
} the swapping process.

Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5

Example 3: Swap Numbers Without Using Temporary Variables


#include <iostream>
using namespace std;
Let us see how this program works:
int main()
Initially, a = 5 and b = 10.
{
Then, we add a and b and store it in a
int a = 5, b = 10;
with the code a = a + b. This means a
cout << "Before swapping." << endl;
= 5 + 10. So, a = 15 now.
cout << "a = " << a << ", b = " << b << endl;
Then we use the code b = a - b. This
a = a + b;
means b = 15 - 10. So, b = 5 now.
b = a - b;
Again, we use the code a = a - b. This
a = a - b;
means a = 15 - 5. So finally, a = 10.
cout << "\nAfter swapping." << endl;
Hence, the numbers have been
cout << "a = " << a << ", b = " << b << endl;
swapped.
return 0;
}

The output of this program is the same as the first program above.

13 | P a g e

You might also like