0% found this document useful (0 votes)
3 views18 pages

Chapter Two

Chapter Two provides an introduction to C++, detailing its evolution from machine language and its purpose in managing complex programs through object-oriented features. It covers the basic structure of a C++ program, including comments, preprocessor directives, the main function, and input/output operations using streams. Additionally, it discusses the compilation process, debugging, and fundamental elements such as keywords, identifiers, data types, and constants.

Uploaded by

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

Chapter Two

Chapter Two provides an introduction to C++, detailing its evolution from machine language and its purpose in managing complex programs through object-oriented features. It covers the basic structure of a C++ program, including comments, preprocessor directives, the main function, and input/output operations using streams. Additionally, it discusses the compilation process, debugging, and fundamental elements such as keywords, identifiers, data types, and constants.

Uploaded by

danigirma310
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CHAPTER TWO

C++ BASICS
2.1. Brief introduction to C++

In the early days of computing, programs were written in machine language, which consists of the primitive
instructions that can be executed directly by the machine. Machine language programs are difficult to
understand, mostly because the structure of machine language reflects the design of the hardware rather than
the needs of programmers. In the mid-1950s, a group of programmers had an idea that profoundly changed
the nature of computing. Would it be possible, they wondered, to write programs that resembled the
mathematical formulas they were trying to compute and have the computer itself translate those formulas
into machine language? In 1955, the initial version of FORTRAN (whose name is an abbreviation of
formula translation), which was the first example of a higher level programming language produced. Since
that time, many new programming languages have been invented, such as COBOL, BASIC, PASCAL, C,
C++, C#, JAVA etc.

C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne Stroustrup in
1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with
Classes." However, in 1983 the name was changed to C++.

Over the years, computer programs have become larger and more complex. Even though
C is an excellent programming language, it has its limits. In C, once a program exceeds from 25,000 to
100,000 lines of code, it becomes so complex that it is difficult to grasp as a totality. The purpose of C++ is
to allow this barrier to be broken. The essence of C++ is to allow the programmer to comprehend and
manage larger, more complex programs because it includes Object Oriented features.

C++ is a high-level language: when you write a program in it, the short hands are sufficiently expressive
that you don’t need to worry about the details of processor instructions. C++ does give access to some
lower-level functionality than other languages (e.g. memory addresses).

2.2. Structure of C++ program


Probably the best way to start learning a programming language is by writing a program. Therefore, here is our
first program:

// my first program in C++


#include <iostream.h>
int main ()
{The above program is the typical program that programmer apprentices write for the first time, and its result
is the<<
cout "Hello World!"
"Hello sentence. It is one of the simplest programs that can be written in C++, but it already
World!";
return 0
contains the fundamental components that every C++ program has. We are going to look line by line at the
}code we have just written:
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short explanations
or observations within the source code itself. In this case, the line is a brief description of what our program
is.

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:

//single line comment


/* Double line comment */

The first of them, known as single line comment, discards everything from where the pair of slash signs (//)
is found up to the end of that same line. 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.

#include <iostream.h>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor. This line uses the preprocessor directive
#include to include the contents of the header file iostream.h in the program. iostream.h is a standard C++
header file and contains definitions for input and output and it is included because its functionality is going
to be used later in the program. Preprocessor directives must be specified in their own line and do not have
to end with a semicolon (;).

Example 1: The line #include <iostream.h> instructs the compiler to include the declaration of the standard
input and output facilities into the program. It is used to copy and insert all the content of the mentioned
header file which is iostream.h into the source program (our own program). Otherwise, the compiler won’t
recognize the operators and the functions used and will refuse to compile the program.

Example 2: Look at the statement in line 5 of the C++ program given as example right to the general format
above. It is cout<<”Hello World”; ‘cout<<’ is an operator whose code is written in the iostream.h header
file. If the content of the header file is not included prior to the compilation process, the compiler will not
recognize this statement at all.

Therefore, this line of the program (as well as all include directives) is used to include header files. Note
that there are a number of header files with their own content and it is possible to include multiple header
files. If you intend to use one of the operators or functions defined in one of these files, include them at the
beginning of your program.
int main ()
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
does not matter whether there are other functions with other names defined before or after it the instructions
contained within this function's definition will always be the first one to be executed in any C++ program.
For that same reason, it is essential that all C++ programs have a main function.

The word main is followed in the code by a pair of parentheses ( ). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions is these
parentheses that follow its name. What is contained within these braces is what the function does when it is
executed.

cout << "Hello World!";


This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output
stream (which usually is the screen).

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. This is the most usual way to
end a C++ console program.

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
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0; }

All in just one line and this would have had exactly the same meaning as the previous code.

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. 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:
// my second program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output: Hello World! I'm a C++ program

int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}

I/O streams
Using the standard input and output library, we will be able to interact with the user by printing messages on
the screen and getting the user's input from the keyboard. C++ uses a convenient abstraction called streams
to perform input and output operations in sequential media such as the screen or the keyboard. A stream is
an object where a program can either insert or extract characters to/from it. The standard C++ library
includes the header file iostream, where the standard input and output stream objects are declared.

Standard Output (cout): By default, the standard output of a program is the screen, and the C++ stream
object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as
<< (two "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

Notice that the sentence in the first instruction is enclosed between double quotes (") because it is a constant
string of characters. Whenever we want to use constant strings of characters we must enclose them between
double quotes (") so that they can be clearly distinguished from variable names. For example, these two
sentences have very different results:
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:
cout << "Hello, " << "I am " << "a C++ statement";

This last statement would print the message Hello, I am a C++ statement on the screen. The utility of
repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables
and constants or more than one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
If we assume the age variable to contain the value 24 and the zipcode variable to contain
90064 the output of the previous statement would be:
Hello, I am 24 years old and my zipcode is 90064

It is important to notice that cout does not add a line break after its output unless we explicitly indicate it,
therefore, the following statements:
cout << "This is a sentence.";
cout << "This is another sentence.";
Will be shown on the screen one following the other without any line breaks between them: This is a
sentence. This is another sentence.

In order to perform a line break on the output we must explicitly insert a new-line character into cout. In C+
+ a new-line character can be specified as \n (backslash, n):
cout << "First sentence.\n ";
cout << "Second sentence.\nThird sentence.";
This produces the following output:
First sentence.
Second sentence.
Third sentence.

Additionally, to add a new-line, you may also use the endl manipulator. For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
Would print out:
First sentence.
Second sentence.

Standard Input (cin): The standard input device is usually the keyboard. Handling the standard input in C+
+ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be
followed by the variable that will store the data that
is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from cin
(the keyboard) in order to store it in this integer variable.

cin can only process the input from the keyboard once the Enter key has been pressed.
Therefore, even if you request a single character, the extraction from cin will not process
the input until the user presses Enter key after the character has been introduced.

You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and b another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.

Compilation process
When you write a program in C++, your first step is to create a file that contains the text of the program,
which is called a source file. Before you can run your program, you need to translate the source file into an
executable form. The first step in that process is to invoke a program called a compiler, which translates the
Source Object file
fileinto an object file containing the corresponding machine-language
source file instructions. This object file
is then combined with other object files to produce an executable file that can be run on the system. The
other object files typically include predefined object files, called libraries that contain the machine-
// my first program in C++ 0100110001000101
language instructions for various operations commonly required by programs. The process of combining all
#include <iostream.h> Compiler 01001001010110001101001001
the()individual object files into an executable file is called linking. The process is illustrated by the diagram
int main 01010001010
{ shown below.
cout << "Hello World!";
return 0;
}

Linker

Executable file

01001100010001001 Other object files/ libraries


01001001010110001
10100100101010001
010 10010100110100100
10101010010101001
01010100
Debugging
Debugging is the process of correcting errors from the program via testing. Errors can be classified into
syntax error and logical error.

Syntax error: syntax refers to the order in which components (token) of the programming language must
come. If there invalid order of token is provided in the language description we call this error as syntax
error. Compiler can easily detect syntax error during compilation. Therefore such error is also called
compilation time error. We can’t compile a source code, which has a syntax error. Therefore syntax error
should be corrected during compilation. The strategy is simple: compile your code, if there is a compilation
error, try to correct it and repeat the process until you get an error free code during compilation.

Logical error: the program designed and compiled without error has an objective. The objective is for any
input the program should process the input and generate an output. However, there may be a case that the
program may not provide the expected output for a known input. Such problem is called logical error.
Logical error can be corrected through intensive testing for various possible cases. Generally getting syntax
error free code is simple but avoiding logical error is a bit difficult and programmer must spent a lot time on
testing.

Various programming language provide advanced debugging tools to correct logical errors.

2.3 Basic elements of C++


2.3.1 Keywords and identifiers
Keywords are certain words reserved by C++. All keywords have fixed meaning which cannot be changed.
All keywords must be written in lowercase and cannot be used as identifiers. The list of C++ keywords is
given in Table 1.

Const Continue float new signed Try

Auto Default for operator sizeof typedef


Break Delete Long private static Union

Case Do Goto protected struct unsigned

Catch Double If public switch virtual

Char Else inline register template Void

Class Enum int return this While

Table 2.1 C++ keywords

Identifiers (Variable name)


Refer to the name of variables, functions, arrays classes, etc. created by the programmer.
They are fundamental requirements of any language. Each language has its own rules for naming these
identifiers. C++ imposes the following rules for creating valid names (identifiers).
Only alphabetic characters, digits and underscores are permitted
The name should start with a letter or an underscore ( _ ) cannot start with a digit.
Names must be all one word (no spaces or hyphens).
Reserved word or names is not permitted.
Upper and lower case letters are distinct. That is, C++ is case sensitive Language.

Example:
salary // valid identifier
salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary

2.3.2. Data Types, Variables, and Constants


Data Types
When programming, we store the variables in our computer's memory, but the computer has to know what
kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a
simple number than to store a single letter or a large number, and they are not going to be interpreted the
same way.

The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can
manage in C++. A byte can store a relatively small amount of data: one single character or a small integer
(generally an integer between 0 and 255). In addition, the computer can manipulate more complex data
types that come from grouping several bytes, such as long numbers or non-integer numbers.
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:

Type Length Range

unsigned char 1 byte 0 to 255

char 1 byte -128 to 127

unsigned int 2 bytes 0 to 65,535

short int 2 bytes -32,768 to 32,767

int 2 bytes -32,768 to 32,767

unsigned long 4 bytes 0 to 4,294,967,295

long 4 bytes -2,147,483,648 to


2,147,483,647

float 4 bytes -3.4x10-38 to 3.4x10+38

double 8 bytes -1.7x10-308 to 1.7x10+308

long double 10 bytes -3.4x10-4932 to 1.1x10+4932

bool 1 byte true or false (top 7 bits are


ignored)

Declaration of variables
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. A declaration is a statement that introduces a name into the program.
It must specify a type for that name.
For example, the declaration
int inch;
Specifies that inch is if type int; that is, int is an integer variable.
int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable of type int with the identifier
a. The second one declares a variable of type float with the identifier mynumber. Once declared, the
variables a and mynumber can be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can declare all of them in a single
statement by separating their identifiers with commas. For example:
int a, b, c; or
int a;
int b;
int c;

Expressions
Anything that evaluates to a value is an expression in C++. An expression is said to return a value. Thus,
3+2; returns the value 5 and so is an expression. All expressions are statements.
The complicated expression: x = a + b;
Thus, this statement is also an expression. Because it is an expression, it can be on the right side of an
assignment operator:
y = x = a + b;
This line is evaluated in the following order: Add a to b. Assign the result of the expression a + b to x.
Assign the result of the assignment expression x = a + b to y. If a, b, x, and y are all integers, and if a has the
value 2 and b has the value 5, both x and y will be assigned the value 7. So, the general form of expression
and variables, evaluated from the right to left, is:
variable = any_expression;

Statements
In C++ a statement controls the sequence of execution, evaluates an expression, or does nothing (the null
statement). All C++ statements end with a semicolon, even the null statement, which is just the semicolon
and nothing else. One of the most common statements is the following assignment statement:
x = a + b;
Unlike in algebra, this statement does not mean that x equals a+b. This is read, "Assign the value of the sum
of a and b to x," or "Assign to x, a+b." Even though this statement is doing two things, it is one statement
and thus has one semicolon. The assignment operator assigns whatever is on the right side of the equal sign
to whatever is on the left side.
Compiler read a statement in the source code it looks for the characters and for the terminating semicolon
and ignores the white space. For example, three of the following examples are same.
x = 2 + 3; or
x=2+3; or
x=
2
+
3;
Whitespace: Whitespace (tabs, spaces, and newlines) is generally ignored in statements. The assignment
statement previously discussed could be written as
x=a+b; or as x = a+ b;

Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a variable
to store a concrete value at the same moment that it is declared. In order to do that, 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, if we want to declare an int variable called a initialized with a value of 0 at the moment in
which it is declared, we could write:
int a = 0;
2.4. Operators
Operators are symbols that tell the computer to perform certain mathematical or logical manipulation. C++
provides many built-in operators for composing expressions. An expression, by the way, is any computation
which yields a value. The several C++ operators can be classified in to:

 Arithmetic operators  Assignment operator

 Relational operators  Increment and Decrement operators

 Logical operators  Conditional operators


Table 2.2 Common operators in C++

2.4.1 Arithmetic Operators


C++ provides five basic arithmetic operators that are summarized in Table 2.3.

Operator Name Example


+ Addition 12 + 4.9 // gives 16.9

- Subtraction 3.98 - 4 // gives -0.02

* Multiplication 2 * 3.4 // gives 6.8

/ Division 9 / 2.0 // gives 4.5


% Remainder 13 % 3 // gives 1

Table 2.3: Arithmetic Operators

Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands.
Generally, if both operands are integers then the result will be an integer. However, if one or both of the
operands are reals then the result will be a real (or double to be exact).

When both operands of the division operator (/) are integers then the division is performed as an integer
division and not the normal division we are used to. Integer division always results in an integer outcome
(i.e., the result is always rounded down).
For example: 9/2 // gives 4, not 4.5!

It is possible for the outcome of an arithmetic operation to be too large for storing in a designated variable. This
situation is called an overflow. The outcome of an overflow is machine-dependent and therefore undefined. It is
illegal to divide a number by zero. This results in a run-time division-by-zero failure, which typically causes the
program to terminate.

2.4. 2 Relational Operators


C++ provides six relational operators for comparing numeric quantities (Table 2.4). Relational operators usually
evaluate to 1 (representing the true outcome) or 0 (representing the false outcome). The operands of a relational
operator must evaluate to a number.

Operator Name Example

== Equality 5 = = 5 // gives 1

!= Inequality 5 ! = 5 // gives 0

< Less Than 5 < 5.5 // gives 1

<= Less Than or Equal 5 <= 5 // gives 1

> Greater Than 5 > 5.5 // gives 0

>= Greater Than or Equal 6.3 >= 5 // gives 1

Table 2.4: Relational Operators


For example,
65 < 70 // gives 1 or true
Relational operators should not be used for comparing strings1, because this will result in the string
addresses being compared, not the string contents. For example, the expression "HELLO" < "BYE" causes
the address of "HELLO" to be compared to the address of "BYE". As these addresses are determined by the
compiler (in a machine-dependent manner), the outcome may be 0 or 1, and is therefore not indicative of the
actual check.
2.4. 3 Logical Operators
C++ provides three logical operators, summarized in Table 2.5, for combining logical expressions. Like the
relational operators, logical operators evaluate to 1 or 0.

1 C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
Operator Name Example

! Logical Negation !(5 == 5) // gives 0

&& Logical AND 5 < 6 && 6 < 6 // gives 0

|| Logical OR 5 < 6 || 6 < 5 // gives 1

Table 2.5: Logical Operators


 Logical Negation is a unary operator, which negates the logical value of its single operand. If its
operand is nonzero it produces 0, and if it is 0 it produces 1.
 Logical AND produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
 Logical OR produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that we talk of zero and nonzero operands (not 0 and 1). In general, any nonzero value can be used to
represent the logical true, whereas only zero represents the logical false. The following are, therefore, all
valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0

2.4.4. Increment/Decrement Operators


The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable. These are summarized in Table 2.6. The examples
assume the following variable definition:
int k = 5;
Operato Name Example
r
++ Auto Increment (prefix) ++k + 10 // gives 16

++ Auto Increment (postfix) k++ + 10 // gives 15


-- Auto Decrement (prefix) --k + 10 // gives 14

-- Auto Decrement (postfix) k-- + 10 // gives 15

Table 2.6: Increment and Decrement Operators


Both operators can be used in prefix and postfix form. The difference is significant. When used in prefix
form, the operator is first applied and the outcome is then used in the expression. When used in the postfix
form, the expression is evaluated first and then the operator applied. Both operators may be applied to
integer as well as real variables, although in practice real variables are rarely useful in this form.

2.4. 5. Assignment Operator (=)


The assignment operator is used for storing a value at some memory location (typically denoted by a
variable). When used, its right operand, which may be an arbitrary expression or a constant, is evaluated and
the outcome is stored in the location denoted by its left operand.

The assignment operator has a number of variants, obtained by combining it with the arithmetic and bitwise
operators (Table 2.7). Assuming that n is an integer variable,
Operator Example Equivalent To

= n = 25

+= n + = 25 n = n + 25

-= n - = 25 n = n – 25

*= n * = 25 n = n * 25

/= n / = 25 n = n / 25

%= n %= 25 n = n % 25

Table 2.7: Assignment operators


An assignment operation is itself an expression whose value is the value stored in its left operand. An
assignment operation can therefore be used as the right operand of another assignment operation. Any
number of assignments can be concatenated in this fashion to form one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
2.4. 6. Conditional (Ternary) operator
The conditional (Ternary) operator takes three operands. It has the general form:
operand1 ? operand2 : operand3
First operand1 is evaluated, which is treated as a logical condition. If the result is nonzero then operand2 is
evaluated and its value is the final result. Otherwise, operand3 is evaluated and its value is the final result.
For example:
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
Note that of the second and the third operands of the conditional operator only one is evaluated. Because a
conditional operation is itself an expression, it may be used as an operand of another conditional operation,
that is, conditional expressions may be nested.
For example:
int m = 1, n = 2, p =3;
int min = (m < n ? (m < p ? m : p): (n < p ? n : p))
2.5. Operator Precedence
The order in which operators are evaluated in an expression is significant and is determined by precedence
rules. These rules divide the C++ operators into a number of precedence levels (see Table 2.8). Operators in
higher levels take precedence over operators in lower levels.
Operator Type Associativity
() parentheses array subscript left to right
[] Unary post increment
++ unary post decrement
--
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
< relational less than relational left to right
< less
=> than or equal to relational
>= greater
== than relational greater than or
!= equal to
relational is equal to relational
is
not equal to
= assignment right to left
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment
Table 2.8 : Operator Precedence Levels
For example, in
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 using brackets. For example, 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 last column of Table 9.
For example, in
a = b += c
the evaluation order is right to left, so first b += c is evaluated, followed by a = b.

Types of errors in C++

Syntax error: This error occurs due to following reason.

i. Not following the grammatical rules used in declaration of identifier.


ii. Not declaring an identifier used in program.
iii. Not terminating statement by semicolon.
iv. Not providing equal number of opening and closing braces etc.
These errors can be rectified by the user as it is displayed while compiling the program.
Logical error: This error won‘t be displayed on the screen. However, it will lead to display
wrong results. Example: An infinite loop. This error leads to abnormal termination of a program
or infinite loop.
Runtime error: This error occurs while running a program by displaying the message listed
below.
i. Division by 0.
ii. Overflow
iii. Underflow
Now let‘s have an example:
Q. Write a corrected code of the following program segment by underlining the error
corrected.
void main()
{

int a,b; cin<<a;

b=a;
cout <<"b=",a;
};

17 | P a g e
Worksheet 2

For each of the problems write a C++ code to perform the required task. Your
program should be based on the flow chart you drawn in the first worksheet.
1. Receive a number and determine whether it is odd or even.
2. Obtain two numbers from the keyboard, and determine and display which (if
either) is the larger of the two numbers.
3. Receive 3 numbers and display them in ascending order from smallest to largest
4. Add the numbers from 1 to 100 and display the sum
5. Add the even numbers between 0 and any positive integer number given by the user.
6. Find the average of two numbers given by the user.
7. Find the average, maximum, minimum, and sum of three numbers given by the user.
8. Find the area of a circle where the radius is provided by the user.
9. Swap the contents of two variables using a third variable.
10. Swap the content of two variables without using a third variable.
11. Read an integer value from the keyboard and display a message indicating if this
number is odd or even.
12. read 10 integers from the keyboard in the range 0 - 100, and count how many
of them are larger than 50, and display this result
13. Take an integer from the user and display the factorial of that number

18 | P a g e

You might also like