Computer 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Chapter Three

Basic Program Construction


Our first step in learning how to program is to learn some C++ basics so that we can implement a program
design using the C++ language. And the best way to start learning a programming language is by writing
a program. To implement an algorithm as a program, we must first learn how to perform certain tasks in
the language we are using.

Basic Structure of a C++ program


Every C++ program has a very similar structure. A simple C++ program consists of four components:
➢ An optional set of preprocessor directives
➢ An optional constant and function declaration section
➢ A main function containing a declaration section and a statement section
➢ Additional C++ functions, we will see about this in detail in the coming chapters

1 //This is a simple C++ program to display Hello world


2 //preprocessor directives
3 #include <iostream>
4 //constants and functions can be declared here
5 //using directive
6 using namespace std;
7 //required main function
8 int main()
9 {
10 cout<<“Hello world”; //output the text
11 return 0;
12 }
13 //others functions can be added here

Sample code 1 Basic structure of C++ program

C++ includes a number of standard libraries. In fact, it is almost impossible to write a C++ program
without using at least one of these libraries. The normal way to make a library available to your
program is with an include directive. An include directive for a standard library has the form:
#include <Library_Name>
For example, the library for console I/O is iostream. So, most of our demonstration programs will begin
#include <iostream>
Compilers (preprocessors) can be very fussy about spacing in include directives. Thus, it is safest to
type an include directive with no extra space: no space before the #, no space after the #, and no spaces
inside the <>.
An include directive is simply an instruction to include the text found in a file at the location of the
include directive. A library name is simply the name of a file that includes all the definition of items in
the library. We will eventually discuss using include directives for things other than standard libraries,
but for now we only need include directives for standard C++ libraries.
C++ has a preprocessor that handles some simple textual manipulation before the text of your program
is given to the compiler. Some people will tell you that include directives are not processed by the
compiler but are processed by a preprocessor.
They’re right, but the difference is more of a word game than anything that need concern you. On
almost all compilers, the preprocessor is called automatically when you compile your program.
Technically speaking only part of the library definition is given in the header file. However, at this
stage, that is not an important distinction, since using the include directive with the header file for a
library will (on almost all systems) cause C++ to automatically add the rest of the library definition.

A namespace is a collection of name definitions. One name, such as a function name, can be given
different definitions in two namespaces. A program can then use one of these namespaces in one place
and the other in another location. For now, we only need to discuss the namespace std. All the standard
libraries, we will be using, place their definitions in the std (standard) namespace. To use any of these
definitions in your program, you must insert the following using directive:
using namespace std;
Thus, a simple program that uses console I/O would begin
#include <iostream>
using namespace std;
All procedure-like entities are called functions in C++. Things that are called procedures, methods,
functions, or subprograms in other languages are all called functions in C++. As shown in the above
sample code, a C++ program is basically just a function called main; when you run a program, the run-
time system automatically invokes the function named main.
A C++ program is really a function definition for a function named main. When the program is run, the
function named main is invoked. The body of the function main is enclosed in braces, {}. When the
program is run, the statements in the braces are executed. The following two lines set up things so that
the libraries with console input and output facilities are available to the program.
#include <iostream>
using namespace std;
The following line says that main is a function with no parameters that returns an int (integer) value:
int main( )
Some compilers will allow you to omit the int or replace it with void, which indicates a function that
does not return a value. However, the above form is the most universally accepted way to start the main
function of a C++ program.
cout<<“Hello world”;
The above line is called C++ statement. A statement is a simple or compound expression that can
actually produce some effect. In fact, this statement performs the only action that generates a visible
effect in our first program. A statement ends with a semicolon character (;).
The program ends when the following statement is executed:
return 0;
This statement ends the invocation of the function main and returns zero as the function’s value which
generally interpreted as the program worked as expected without any errors during its execution.. This
statement causes the main function to finish. According to the ANSI/ISO C++ standard, this statement
is not required, but many compilers still require it.
In the previous example, lines that start with two slash signs (//) are considered as 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. This line is called comment line. We can
have two kinds of comment lines:
• Line comment, which have been used in the previous example.
• Block comment, which is used when programmer has more than one line comments. It uses a
symbol at the beginning /* and has a symbol */ when the programmer finishes the comment.
o Example: /* This is my first program
C++ programming*/
The output of the previous example is: Hello world
Sample code 2 contains a simple C++ program and two possible screen displays that might be
generated when a user runs the program.
1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 int numberOfLanguages;
6 cout << "Hello reader.\n"
7 << "Welcome to C++.\n";
8 cout << "How many programming languages have you used? ";
9 cin >> numberOfLanguages;

10 if (numberOfLanguages < 1)
11 cout << "Read the preface. You may prefer\n"
12 << "a more elementary book by the same author.\n";
13 else
14 cout << "Enjoy the book.\n";
15 return 0;
16 }

Sample code 2 A Sample c++ program

Hello reader.
Welcome to C++.
How many programming languages have you used? 0  User types in 0 on the keyboard
Read the preface. You may prefer
a more elementary book by the same author.

output 1 output for the sample code 2

The following line from Sample code 2 declares the variable numberOfLanguages and its called
variable declaration.
int numberOfLanguages;
The type int is one of the C++ types for whole numbers (integers).
The use of cin and cout for console I/O is to input data from the user and to display output on the screen
respectively.
For example, consider the following two lines from Sample code 2:
cout << "How many programming languages have you used? ";
cin >> numberOfLanguages;
The first line outputs the text within the quotation marks to the screen i.e. How many programming
languages have you used?. The second line reads in a number that the user enters at the keyboard and
sets the value of the variable numberOfLanguages to this number.
The extraction operator (<<) and the insertion operator (>>) can be used more than once in a same
sentence as below.
cout << "Read the preface. You may prefer\n"
<< "a more elementary book by the same author.\n";
The above lines output two strings instead of just one string. The symbolism \n is the newline character,
which instructs the computer to start a new line of output.
Although you may not yet be certain of the exact details of how to write such statements, you can
probably guess the meaning of the if-else statement. The details will be explained in the coming
chapter.
Built-in Data Types
A built-in data type is a data type for which the programming language provides built-in support. Data
used by our program are stored in the computer memory. But the computer must know what we want to
store in the memory, since storing a simple number, a letter or a large number is not going to occupy
the same space in the memory. In order to use our finite memory effectively, we will specify what kind
of data to store which, in turn, will reserve the right memory for that particular data. Some of them are:
• For Boolean values – bool
• For characters – char
• For integers – short, int and long
• For floating point – float, double and long double
Table 2 simple types

White characters/Escape sequences [special characters]


\n ---> new line \a --->alert (beep)
\r --->carriage return \ ‘ --->single quotes
\t --->tabulation \” --->double quotes
\v --->vertical tabulation \ ? --->question mark
\b ---->back space \\ ---> back slash
\f ---> page feed

VARIABLE
A variable in c++ is something that stores data. The contents of a variable is changeable, it’s not fixed.
Before using a variable, it has to always be declared first. The purpose of declaring a variable is so that
the computer can set aside enough memory to store a value that the programmer is going to put in the
variable that is declared.

The name of a variable (constant and function if defined a program) is called an identifier. A C++
identifier must start with either a letter or the underscore symbol, and all the rest of the characters must
be letters, digits, or the underscore symbol. For example, the following are all valid identifiers:
x x1 x_1 _abc ABC123z7 sum RATE count data2 bigBonus
All the above names are legal and would be accepted by the compiler, but the first five are poor choices
for identifiers because they are not descriptive of the identifier’s use. It is recommended that identifiers
be descriptive of the variable they are named for.
None of the following are legal identifiers, and all would be rejected by the compiler:
12 3X %change data-1 myfirst.c PROG.CPP
The first two are not allowed because they do not start with a letter or an underscore. The remaining four
are not identifiers because they contain symbols other than letters, digits, and the underscore symbol.
Although it is legal to start an identifier with an underscore, you should avoid doing so, because identifiers
starting with an underscore are informally reserved for system identifiers and standard libraries.
C++ is a case-sensitive language; that is, it distinguishes between uppercase and lowercase letters in the
spelling of identifiers. Hence, the following are three distinct identifiers and could be used to name three
distinct variables:
rate, RATE and Rate
However, it is not a good idea to use two such variants in the same program, since that might be confusing.
Although it is not required by C++, variables are usually spelled with their first letter in lowercase. The
predefined identifiers, such as main, cin, cout, and so forth, must be spelled in all lowercase letters.
A C++ identifier can be of any length, although some compilers will ignore all characters after some
(large) specified number of initial characters.
There is a special class of identifiers, called keywords or reserved words, which have a predefined
meaning in C++ and cannot be used as names for variables or anything else. Some predefined words,
such as cin and cout, are not keywords. These predefined words are not part of the core C++ language,
and you are allowed to redefine them. Although these predefined words are not keywords, they are
defined in libraries required by the C++ language standard. Needless to say, using a predefined identifier
for anything other than its standard meaning can be confusing and dangerous and thus should be avoided.
The safest and easiest practice is to treat all predefined identifiers as if they were keywords.
Table 3 Some list of c++ key words

asm continue float new signed Try

auto default for operator sizeof typedef

break delete friend 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 volatile

const extern long short throw While

VARIABLE DECLARATIONS
All variables must be declared before they are used. The syntax for variable declarations is as follows.
Syntax
Type_Name Variable_Name_1, Variable_Name_2,. . .;
Example 1:
int count, numberOfDragons, numberOfTrolls;
double distance;
Example 2 :
#include<iostream>
using namespace std;
int main()
{
int radius=6; //assigning value to the variable
float PI=3.14;
float circumference;
circumference=2*PI*radius;
cout<<"Circumference = "<<circumference;
return 0;
}
The output is : Circumference = 37.68

NAMING CONSTANTS
C++ provides a way of marking an initialized variable so that it cannot be changed. If your program
tries to change one of these variables, it produces an error condition. To mark a variable declaration, so
that the value of the variable cannot be changed, precede the declaration with the word const (which is
an abbreviation of constant).
For example:
const int BRANCH_COUNT = 10;
const int WINDOW_COUNT = 10;
The word const is often called a modifier, because it modifies (restricts) the variables being declared. A
variable declared using the const modifier is often called a declared constant.
Constants can also be defined.
Example: #define rate 30

The above example will define rate to only hold the data 30.

Example:
#include<iostream>
using namespace std;
int main() {
int radius=6; //assigning value to the variable
const float PI=3.14;
float circumference;
//PI=3.145; If it weren’t commented, this statement was going to be an error
circumference=2*PI*radius;
cout<<"Circumference = "<<circumference;
return 0; }
Arithmetic Operators
C++ provides five basic arithmetic operators.
Table 1 arithmetic operators

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

In a division, depending on the variable type, the result will also change. From the above example, if
the variable is a floating point, it will store 4.5; but if the variable is an integer type, it can only store 4.

Relational Operators
C++ provides six relational operators for comparing numeric quantities.
Table 2 relational operators

Operator Name Example


== Equality 5 == 5 // gives True

!= Inequality 5! = 5 // gives False

< Less Than 5 < 5.5 // gives True

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

> Greater Than 5 > 5.5 // gives False


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

Logical Operators
C++ provides three logical operators for combining logical expression.
Table 3 Logical Operators

Operator Name Example

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

&& Logical And 5 < 6 && 6 < 7 // gives 1

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


Increment/Decrement Operators
The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
The examples assume the following variable definition:
int k = 5;
Table 4 Increment and decrement operators

Operator Name Example


++ 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

ASSIGNMENT OPERATOR
The assignment operator is used for storing a value at some memory location (typically denoted by a
variable). Its left operand should be a value, and its right operand may be an arbitrary expression.
Table 5 Assignment operator

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
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
CONDITIONAL OPERATOR ( ? )
The conditional operator evaluates an expression and returns a different value according to the
evaluated expression, depending on whether it is true or false.
Syntax is: condition ? result1 : result2
If the condition is true, it will return result1; else if it is false, it will return result2.
Example: 3==4? 11:30; // it will return 30 since the condition is false
{
int a=9 , b=3 ,c=4;
a=(b>a-4)?a++: --c;
cout<<a; // it will have an output : 3
}
COMMA OPERATOR (,)
This command is used to combine multiple expressions. It evaluates expressions from left to right and
return the value of the right most expression.

Example: a=(b=3,b+2) // a=5 and b= 3;

Simple and Compound Statements


A simple statement is a computation terminated by a semicolon. Variable definitions and semicolon
terminated expressions are examples:
int i; // declaration statement
++i;
double d = 10.5; // declaration statement
d + 5;
Multiple statements can be combined into a compound statement by enclosing them within braces. For
example:
{
int min, i = 10, j = 20;
min = (i < j ? i : j);
cout << min << '\n’;
}
A compound statement may contain variable definitions and defines a scope for them. It is also called a
block.
TYPE CONVERSION

It is the process of converting one type into another. Converting an expression of a given type into
another is called type casting.

There are two ways of achieving the type conversion, namely:

- Automatic Conversion or Implicit Conversion


- Type casting or Explicit Conversion

Automatic Conversion or Implicit Conversion

This is not done using any conversions or operators. In other words, value gets automatically
converted to the specific type in which it is assigned.

Example: short x=60;


int y;
y=x;

In the above example, the data type short declared for the variable x is converted to int and is
assigned to the integer variable y automatically.

Type casting or Explicit Conversion

Explicit conversion can be done using type cast operator and the general syntax for doing this is
using either one of them:

datatype (expression);

(datatype) expression;

The datatype is the type of data that you want your expression to be changed to.

Example: float b = 10.10;

int a;

a = int(b); //will assign a 10 after converting b to an integer

LIBRARY FUNCTIONS

A function is a collection of statements that perform a specific task. There are two types of
functions in C++. These are:

• Predefined function
• User defined function
In this chapter, predefined function is going to be covered. User defined function will be
discussed in later chapter.

As its name suggests, predefined functions are functions whose tasks are already defined. A
programmer can call this functions and that particular task that the function represents will be
accomplished. Its actual code is hidden away within the Standard C++ Library.

Standard C++ library function is a collection of pre-defined functions and other program elements
which are accessed through header files.

Example: a=sqrt(b); //defined in <cmath>

From the above example, sqrt is a function name and b is function argument. Square root function
is activated by the function call, sqrt(b). This statement will return the square root of b and,
because of the assignment operator, the result will be assigned to a.

Some of the examples of the libraries available are cmath, string and iostream.

Some of the functions available are:

Example

#include <iostream>
#include <cmath> /* necessary to use mathematical functions in library */
#define pi 22.0/7
using namespace std;
void main ()
{
double x= pi/6; // 30 degree = pi/6 in radian
cout<<sin(x)<<endl;
}
Exercises

1. Write a C++ program that prints out your name.


2. What would be the output of the following program
#include <iostream>
using namespace std;
void main ()
{
int i=2, j=8;
cout<<--i<<endl;
cout<<i++<<endl;
cout<<i<<endl;
cout<<j++<<endl;
cout<<--j<<endl;
}
3.

You might also like