Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Programming

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

Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Unit I: Introduction to Programming


Introduction to computer and programming
A computer is a device that can perform computations and make logical decisions
phenomenally faster than human beings can. Many of today’s personal computers can
perform billions of calculations in one second—more than a human can perform in a
lifetime. Supercomputers are already performing thousands of trillions (quadrillions) of
instructions per second! To put that in perspective, a quadrillion-instruction-per-second
computer can perform in one second more than 100,000 calculations for every person on
the planet!
And—these “upper limits” are growing quickly!

Computers process data under the control of sets of instructions called computer
programs. These programs guide the computer through orderly sets of actions specified by
people called computer programmers. The programs that run on a computer are referred
to as software.

A computer consists of various devices referred to as hardware (e.g., the keyboard, screen,
mouse, hard disks, memory, DVDs and processing units). Computing costs are dropping
dramatically, owing to rapid developments in hardware and software technologies.
Computers that might have filled large rooms and cost millions of dollars decades ago are
now inscribed on silicon chips smaller than a fingernail, costing perhaps a few dollars each.
Ironically, silicon is one of the most abundant materials—it’s an ingredient in common sand.
Silicon-chip technology has made computing so economical that more than a billion
general-purpose computers are in use worldwide

Any computer can directly understand only its own machine language, defined by its
hardware design. Machine languages generally consist of strings of numbers (ultimately
reduced to 1s and 0s) that instruct computers to perform their most elementary operations
one at a time. Machine languages are machine dependent (a particular machine language
can be used on only one type of computer). Such languages are cumbersome for humans.

Programming in machine language was simply too slow and tedious for most programmers.
Computer usage increased rapidly with the advent of assembly languages, but programmers
still had to use many instructions to accomplish even the simplest tasks. To speed the
programming process, high-level languages were developed in which single statements
could be written to accomplish substantial tasks. Translator programs called compilers
convert high-level language programs into machine language. High-level languages allow

Lecture Note-Cosc1013 Page 1


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

you to write instructions that look almost like every day English and contain commonly used
mathematical notations.
Instead of using the strings of numbers that computers could directly understand,
programmers began using English-like abbreviations to represent elementary operations.
These abbreviations formed the basis of assembly languages. Translator programs called
assemblers were developed to convert early assembly-language programs to machine
language at computer speeds.

From the programmer’s standpoint, high-level languages are preferable to machine and
assembly languages. C++, C, Microsoft’s .NET languages (e.g., Visual Basic, Visual C++ and
Visual C#) and Java are among the most widely used high-level programming languages.
Compiling a large high-level language program into machine language can take a
considerable amount of computer time. Interpreter programs were developed to execute
high-level language programs directly (without the delay of compilation), although slower
than compiled programs run.

Software
You do not normally talk directly to the computer, but communicate with it through an operating system.
The operating system allocates the computer’s resources to the different tasks that the computer must
accomplish. The operating system is actually a program, but it is perhaps better to think of it as your chief
servant. It is in charge of all your other servant programs, and it delivers your requests to them. If you
want to run a program, you tell the operating system the name of the file that contains it, and the
operating system runs the program. If you want to edit a file, you tell the operating system the name of
the file and it starts up the editor to work on that file. To most users the operating system is the
computer. Most users never see the computer without its operating system. The names of some
common operating systems are UNIX, DOS, Linux, Windows, Mac OS, and VMS.
A program is a set of instructions for a computer to follow. The input to a computer can be thought of as
consisting of two parts, a program and some data. The computer follows the instructions in the program,
and in that way, performs some process. The data is what we conceptualize as the input to the program.
For example, if the program adds two numbers, then the two numbers are the data. In other words, the
data is the input to the program, and both the program and the data are input to the computer (usually
via the operating system). Whenever we give a computer both a program to follow and some data for
the program, we are said to be running the program on the data, and the computer is said to execute the
program on the data. The word data also has a much more general meaning than the one we have just
given it. In its most general sense it means any information available to the computer. The word is
commonly used in both the narrow sense and the more general sense.
High-Level Languages
There are many languages for writing programs. In this text we will discuss the C++ programming
language and use it to write our programs. C++ is a high level language, as are most of the other
Lecture Note-Cosc1013 Page 2
Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

programming languages you are likely to have heard of, such as C, Java, Pascal, Visual Basic, FORTRAN,
COBOL, Lisp, Scheme, and Ada. High-level languages resemble human languages in many ways. They are
designed to be easy for human beings to write programs in and to be easy for human beings to read. A
high-level language, such as C++, contains instructions that are much more complicated than the simple
instructions a computer’s processor (CPU) is capable of following.
The kind of language a computer can understand is called a low-level language. The exact details of low-
level languages differ from one kind of computer to another. A typical low-level instruction might be the
following:
ADD X Y Z
This instruction might mean “Add the number in the memory location called X to the number in the
memory location called Y, and place the result in the memory location called Z.” The above sample
instruction is written in what is called assembly language. Although assembly language is almost the
same as the language understood by the computer, it must undergo one simple translation before the
computer can understand it. In order to get a computer to follow an assembly language instruction, the
words need to be translated into strings of zeros and ones. For example, the word ADD might translate to
0110, the X might translate to 1001, the Y to 1010, and the Z to 1011. The version of the above
instruction that the computer ultimately follows would then be:
0110 1001 1010 1011
Assembly language instructions and their translation into zeros and ones differ from machine to
machine.
Programs written in the form of zeros and ones are said to be written in machine language, because that
is the version of the program that the computer (the machine) actually reads and follows. Assembly
language and machine language are almost the same thing, and the distinction between them will not be
important to us. The important distinction is that between machine language and high-level languages
like C++: Any high-level language program must be translated into machine language before the
computer can understand and follow the program.
Compilers
A program that translates a high-level language like C++ to a machine language is called a compiler. A
compiler is thus a somewhat peculiar sort of program, in that its input or data is some other program,
and its output is yet another program. To avoid confusion, the input program is usually called the source
program or source code, and the translated version produced by the compiler is called the object
program or object code. The word code is frequently used to mean a program or a part of a program,
and this usage is particularly common when referring to object programs. Now, suppose you want to run
a C++ program that you have written. In order to get the computer to follow your C++ instructions,
proceed as follows. First, run the compiler using your C++ program as data. Notice that in this case, your
C++ program is not being treated as a set of instructions. To the compiler, your C++ program is just a long
string of characters. The output will be another long string of characters, which is the machine-language
equivalent of your C++ program.

Lecture Note-Cosc1013 Page 3


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Next, run this machine-language program on what we normally think of as the data for the C++ program.
The output will be what we normally conceptualize as the output of the C++ program.

Any C++ program you write will use some operations (such as input and output routines) that have
already been programmed for you. These items that are already programmed for you (like input and
output routines) are already compiled and have their object code waiting to be combined with your
program’s object code to produce a complete machine-language program that can be run on the
computer. Another program, called a linker, combines the object code for these program pieces with the
object code that the compiler produced from your C++ program. In routine cases, many systems will do
this linking for you automatically. Thus, you may not need to worry about linking in very simple cases. In
routine cases, many systems will do this linking for you automatically. Thus, you may not need to worry
about linking in very simple cases.

Algorithm development and representation


Computer problem solving is a complicated process requiring careful planning and attention to
detail. The vehicle for the computer solution to a problem is a set of explicit and unambiguous
instructions called a program and expressed in a programming language. A program is a sequence
of instructions that determine the operations to be carried out by the machine in order to solve a
particular problem. There are five stages of software/program development. They are Analysis,
Algorithm design & Flow chart, Coding, Implementation, and Maintenance.
Stages of Program Development
There are five stages of program development: namely, Analysis, Algorithm & Flow chart design
Coding, Implementation, and Maintenance.
Analysis

Lecture Note-Cosc1013 Page 4


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Analysis stage requires a thorough understanding of the problem at hand and analysis of the data
and procedures needed to achieve the desired result. In analysis stage, therefore, what we must do
is work out what must be done rather than how to do it.
 What input data are needed to the problem?
 What procedures needed to achieve the result?
 What outputs data are expected?
Algorithm design and flowchart
Once the requirements of the program are defined, the next stage is to design an algorithm to solve
the problem. An algorithm is a finite set of steps which, if followed accomplishes a particular task.
An algorithm is a map or an outline of a solution which shows the precise order in which the
program will execute individual functions to arrive at the solution. It is language independent. An
algorithm can be expressed in many ways. Here, we only consider two such methods:
Narrative (pseudocode) and Flowchart. English is often used to describe or narrate the algorithm.
There is no need to follow any rules about how to write it. Instead we use pseudo code which is free
form list of statements that shows the sequence of instructions to follow.
Flowchart
A flowchart consists of an ordered set of standard symbols (mostly, geometrical shapes) which
represent operations, data flow or equipment.
A flowchart is a diagram consisting of labeled symbols, together with arrows connecting one
symbol to another. It is a means of showing the sequence of steps of an algorithm.
A program flowchart shows the operations and logical decisions of a computer program. The most
significant advantage of flowcharts is a clear presentation of the flow of control in the algorithm, i.e.
the sequence in which operations are performed. Flowcharts allow the reader to follow the logic of
the algorithm more easily than would a linear description in English. Another advantage of
flowchart is it doesn’t depend on any particular programming language, so that it can used, to
translate an algorithm to more than one programming language.
A basic set of established flowchart symbols is:
Decision
Processing Input/output

START/STOP

Connector Flow lines

The symbols have the following meanings:


Processing: one or more computational tasks are to be performed sequentially.

Lecture Note-Cosc1013 Page 5


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Input/output: data are to be read into the computer memory from an input device or data are to
be passed from the memory to an output device.
Decision: –It usually contains a question within it. There are typically two output paths: one if the
answer to the question is yes ( true) , and the other if the answer is no ( false). The path to be
followed is selected during the execution by testing whether or not the condition specified within
the outline is fulfilled.
Terminals: appears either at the beginning of a flowchart (and contains the word "start") or at its
conclusion (and contains "stop"). It represents the Start and End of a program.
Connector: makes it possible to separate a flowchart into parts.
Flow lines: is used to indicate the direction of logical flow. (A path from one operation to another)
DESIGN AND IMPLEMENTATION OF ALGORITHMS
An algorithm is a finite set of instruction that specify a sequence of operations to be carried out in
order to solve a specific problem or class of problems. It is just a tool for solving a problem. All the
tasks that can be carried out by a computer can be stated as algorithms. For one problem there may
be a lot of algorithms that help to solve the problem, but the algorithm that we select must be
powerful, easy to maintain, and efficient (it doesn’t take too much space and time)

Once an algorithm is designed, it is coded in a programming language and computer executes the
program. An algorithm consists of a set of explicit and unambiguous finite steps which, when carried
out for a given set of initial conditions, produce the corresponding output and terminate in a fixed
amount of time. By unambiguity it is meant that each step should be defined precisely i.e., it should
have only one meaning. This definition is further classified with some more features.
An algorithm has five important features.
 Finiteness: An algorithm terminates after a fixed number of steps.
 Definiteness: Each step of the algorithm is precisely defined, i.e., the actions to be carried
out should be specified unambiguously.
 Effectiveness: All the operations used in the algorithm are basic (division, multiplication,
comparison, etc.) and can be performed exactly in a fixed duration of time.
 Input: An algorithm has certain precise inputs, i.e. quantities, which are specified to it
initially, before the execution of the algorithm begins.
 Output: An algorithm has one or more outputs, that is, the results of operations which have
a specified relation to the inputs

Examples of Algorithm Development

1) Algorithm to add two numbers.


Step 1: START
Step 2: Read two numbers n1 and n2.
Step 3: Sum ← n1 + n2

Lecture Note-Cosc1013 Page 6


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Step 4: Print Sum


Step 5: STOP
2) Algorithm to find largest number from two numbers.
Step 1: START
Step 2: Read n1 and n2.
Step 3: If n1 > n2 go to step 5
Step 4: Big←n2,go to step 6
Step 5: Big ← n1
Step 6: Print Big
Step 7: STOP
3) Algorithm to find largest number from three numbers.
Step 1: START
Step 2: Read n1, n2 and n3.
Step 3: If n1 > n2 and n1 > n3, go to step 6
Step 4: If n2 > n1 and n2 > n3, go to step 7
Step 5: Big ←n3, go to step 8
Step 6:Big ← n1 , go to step 8
Step 7:Big ← n2
Step 8: Print Big
Step 9: STOP.

4) Algorithm to find sum of N positive integer numbers.

Step 1: START
Step 2: Read N
Step 3: Sum ← 0,
Step 4: Count ← 0
Step 5: Read Num
Step 6: Sum←Sum + Num
Step 7: count ← count +1
Step 8: If Count < N then goto step5
Step 9: Print Sum
Step 10: Stop

Flow Chart Development


1. A flowchart to add two numbers

Lecture Note-Cosc1013 Page 7


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

2. A Flowchart to find largest of


two numbers.

Coding
The flowchart is independent of programming language. Now at this stage we translate each steps
described in the flowchart (algorithm description) to an equivalent instruction of target

Lecture Note-Cosc1013 Page 8


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

programming language, that means, for example if we want to write in FORTRAN program language,
each step will be described by an equivalent FORTRAN instruction (Statement).
Implementation
Once the program is written, the next step is to implement it. Program implementation involves
three steps, namely, debugging (the process of removing errors), testing (a check of correctness),
and documenting the program (to aid the maintenance of a program during its life time). Every
program contains bugs that can range from simple mistakes in the language usage (syntax errors) up
to complex flaws in the algorithm (logic errors).
Maintenance
There are many reasons why programs must be continually modified and maintained, like changing
conditions, new user needs, previously undiscovered bugs (errors). Maintenance may involve all
steps from requirements analysis to testing.

Translation and Execution


The only language that the computer understands is the machine language. Therefore any program
that is written in either low-level or high level language must be translated to machine code so that
the computer could process it.

A program written in High-level or Assembly is called Source code or Source program and, the
translated machine code is called the object code or object program. Programs that translate a
program written in high level language and Assembly to machine code program are called
translators. There are three types of translators; assembler, interpreter, and compiler.

 Source code: High-level language instructions.


 Compiler: System software which translates high-level language instructions into machine
language or object code. The compiler translates source code once and produces a complete
machine language program.
 Object code: Translated instructions ready for computer.
 An assembler is a software tool for translating low-level language (assembly language) into
machine language.
The translator not only translates the instructions into machine code but also it detects whether the
program fulfills the syntax of the programming language. A program passes through different stages
before it carries out its function. First the program will be translated to object code (compilation
time), then it will be loaded to the memory and finally it will be executed (run time) or carries out its
function.
Basic Programming Tools
The three basic building blocks, that is essential to develop a solution to a problem are:

1. Sequential executions where instructions are performed one after the other.
Lecture Note-Cosc1013 Page 9
Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

2. Branching operations where a decision is made to perform one block of instructions or


another.
3. Looping operations where a block of instructions is repeated. There are two types of loops.
The first is the conditional loop where we do not know in advance how many times
something is to be repeated. The second type is the counted loop where we do know in
advance how many times to repeat the solution.
I. Sequential Execution of Instructions
Sequential instructions are executed one after the other. The computer begins with the first
instruction and performs the indicated operation, then moves to the next instruction and so on.

Illustration: 1 - An algorithm and a flowchart to compute the area of a rectangle whose length is ‘l’
and breadth is ‘b’. Flowchart
START

Algorithm
Read l,b
Step 1: START
Step 2: Obtain (input) the length, call it l
Step 3: Obtain (input) the breadth, call it b Area ← l*b

Step 4: Compute l*b, call it Area


Step 5: Display Area Display Area
Step 6: STOP

Stop

START
Illustration: 2- To allow for repeated calculation of the area of a rectangle
whose length is ‘l’ and breadth is ‘b’, rewrite the above algorithm and
Read l,b
flowchart. Allow different values of ‘l’ and ‘b’ before each calculation of
area.
Area ← l*b

Lecture Note-Cosc1013 Page 10 Display


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Algorithm Flowchart

Step 1: START
Step 2: Read length, call it l
Step 3: Read breadth, call it b
Step 4: compute l*b, call it Area
Step 5: Display Area
Step 6: Go to step 2
Note: Here in effect we created a loop. The series of instructions to calculate ‘area’ is reused over
and over again, each time with a different set of input data. But here it is an infinite loop. There is no
way to stop the repeated calculations except to pull the plug of the computer. There fore using this
type of unconditional transfer (Go to) to construct a loop is generally not a good idea. In almost all
cases where an unconditional loop seems useful, one of the other control structures (loops or
branches) can be substituted and in fact it is preferred
II. Branching Operations
With sequential instructions there is no possibility of skipping over one instruction. A branch is a
point in a program where the computer will make a decision about which set of instructions to
execute next. The question that we use to make the decision about which branch to take must be
set up so that the answers can only be yes or no. Depending on the answer to the question, control
flows in one direction or the other.
Illustration: Construct an algorithm and flowchart to read two numbers and determine which is
large.
Algorithm
Step 1: START
Step 2: Read two numbers A and B.
Step 3: If A > B then go to step 6
Step 4: Display B is largest.
Step 5: go to step 7
Step 6: Display A is largest
Step 7: STOP
Flowchart

Lecture Note-Cosc1013 Page 11


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Note that only one block of instructions is executed, not both. After one block or other executes, the
two paths merge (at the circle) and control transfers to the next instruction. We could have several
loops inside each block since we are not limited to just one instruction.
Nesting of Branching Operations
There are many times when we need to choose between more than two alternatives. One of the
solutions to this is nesting of instructions.
Illustration
Construct an algorithm and flowchart to see if a number ‘n’ is negative, positive, or zero
Algorithm Flowchart
Step 1: START
Step 2: Read in ‘n’
Step 3: Is n<0
Step 4: If yes, go to step 11
Step 5: Is n=0
Step 6: If yes, go to step 9
Step 7: Print “Positive”
Step 8: go to step 12
Step 9: Print “Zero”
Step 10: go to step 12
Step 11: Print “Negative”
Step 12: STOP
III. LOOPS

Loops are the third major type of control structure that we need to examine. There are 2 different
types of loops, the counted loop and the conditional loop. The counted loop repeats a
predetermined number of times while the conditional loop repeats until a condition is satisfied.

 In the counted loop a counter keeps track of the loop executions. Once the counter reaches
a predetermined number, the loop terminates. Number of loop executions is set before the
loop begins and cannot be changed while the loop is running.
 The conditional loop has no predetermined stopping point. Rather, each time through the
loop the program performs a test to determine when to stop. Also the quantity being used
for the test can change while the loop executes.
 The variable used to control the loop can be referred to as Loop Control Variable (LCV).

Lecture Note-Cosc1013 Page 12


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

 Flowchart symbol for loop is hexagon. Inside the loop is the start and stop values for LCV.
Also a step value is included from which the computer decides how many times to execute
the loop. Inside the loop is the body which can consist of any number of instructions. When
the loop finishes, the control transfers to the first statement outside the loop.
 With counted loops, it’s a must to know in advance how many times the loop will execute.
But if this information is not available and yet the problem demands a loop means, we can
make use of conditional loop, where the machine will check every time through the loop to
see whether it should be repeated or not.
 In conditional loop, the programmer must change the Loop control variable.

Start =…

Stop=…

Illustration

Ex. An algorithm and flowchart to print out the numbers 1 to 100 and their squares.

Algorithm Flowchart

Start 1: START

Start 2: Loop (LCV start=1;stop=100,step=1)

Step 3: Print LCV, LCV2 value

Step 4: End loop

Step 5: STOP

Quick quize
Construct an algorithm and a flowchart for the following:
1. To find the smallest number from three numbers.
2. To read in x, y and z and then compute the value of xyz.
3. To determine if a whole number is odd or even.

Lecture Note-Cosc1013 Page 13


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

4. To print a prompt message “good morning”.


5. To find the sum of first n even numbers.
6. To find the sum of digits of a given number.
7. To print out a list of first n even numbers and their squares.
8. To find the sum of n positive numbers.
9. To find the biggest among n numbers.
10. To find the factorial of a given number.
11. To generate Fibonacci series (1, 1, 2, 3, 5, 8, 13…)

Unit-II: C++ basics


History of C++

C++ is an Object Oriented Programming Language. It was initially named ‘C with classes’, C++ was
developed by Bjarne Stroustrup at AT&T Bell laboratories in Murray Hill, New Jersey, USA, in the
early eighties. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine

Lecture Note-Cosc1013 Page 14


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

the best of both languages and create a more powerful language that could support object-oriented
programming features and still retain the power and elegance of C. The result was C++. Stroustrup
called the new langrage ‘C with classes’. However, later in 1983, the name was changed to C++. C++
is a super set of C. Therefore, almost all C programs can be written in C++.

List of Compilers:

1. Borland C+ + & Turbo C+ + available from Borland International for DOS & OS/2.
2. Zortech C+ + from Zortech International on DOS.
3. Microsoft Visual C+ + by Microsoft Corp.
4. GNU C+ + usually called as G++.
Layout of a Simple C++ Program

The general form of a simple C++ program is shown in Display 2.1. As far as the compiler is
concerned, the line breaks and spacing need not be as shown there and in our examples. The
compiler will accept any reasonable pattern of line breaks and indentation. In fact, the compiler will
even accept most unreasonable patterns of line breaks and indentation. However, a program
should always be laid out so that it is easy to read. Placing the opening brace, { , on a line by itself
and also placing the closing brace, } , on a line by itself will make these punctuations easy to find.
Indenting each statement and placing each statement on a separate line makes it easy to see what
the program instructions are. Later on, some of our statements will be too long to fit on one line and
then we will use a slight variant of this pattern for indenting and line breaks. You should follow the
pattern set by the examples in this material.

DISPLAY 2.1 Layout of a Simple C++ Program

1 #include <iostream.h>

2 int main( )

3{

4 Variable_Declarations

5 Statement_1

6 Statement_2

7 ...

8 Statement_Last

9 return 0;

Lecture Note-Cosc1013 Page 15


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

10 }

The variable declarations are on the line that begins with the word int. As we will see in the next
sections, you need not place all your variable declarations at the beginning of your program, but
that is a good default location for them. Unless you have a reason to place them somewhere else,
place them at the start of your program as shown in Display 2.1. The statements are the instructions
that are followed by the computer. In Display 2.2 in the following page, the statements are the lines
that begin with cout or cin, and the one line that begins with c followed by an equal sign.
Statements are often called executable statements. We will use the terms statement and
executable statement interchangeably. Notice that each of the statements we have seen ends with a
semicolon. The semicolon in statements is used in more or less the same way that the period is used
in English sentences; it marks the end of a statement.

For now you can view the first few lines as a funny way to say “this is the beginning of the
program.” But we can explain them in a bit more detail. The first line #include <iostream.h> is called
an include directive. It tells the compiler where to find information about certain items that are
used in your program. In this case iostream.h is the name of a library that contains the definitions of
the routines that handle input from the keyboard and output to the screen; iostream.h is a file that
contains some basic information about this library. A linker program combines the object code for
the library iostream.h and the object code for the program you write. For the library iostream.h this
will probably happen automatically on your system. You will eventually use other libraries as well,
and when you use them, they will have to be named in directives at the start of your program. For
other libraries, you may need to do more than just place an include directive in your program, but in
order to use any library in your program, you will always need to at least place an include directive
for that library in your program. Directives always begin with the symbol #. Some compilers require
that directives have no spaces around the #; so it is always safest to place the # at the very start of
the line and not include any space between the # and the word include. The following line further
explains the include directive that we just explained.

The second and third nonblank lines, shown next, simply say that the main part of the program
starts here:

int main( )

The correct term is main function, rather than main part,. The braces { and } mark the beginning and
end of the main part of the program. They need not be on a line by themselves, but that is the way
to make them easy to find and we will therefore always place each of them on a line by itself. The

Lecture Note-Cosc1013 Page 16


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

next-to-last line return 0; says to “end the program when you get to here.” This line need not be the
last thing in the program, but in a very simple program it makes no sense to place it anywhere else.
Some compilers will allow you to omit this line and will figure out that the program ends when there
are no more statements to execute. However, other compilers will insist that you include this line,
so it is best to get in the habit of including it, even if your compiler is happy without it. This line is
called a return statement and is considered to be an executable statement because it tells the
computer to do something; specifically, it tells the computer to end the program. The number 0 has
no intuitive significance to us yet, but must be there; its meaning will become clear as you learn
more about C++. Note that even though the return statement says to end the program, you still
must add a closing brace } at the end of the main part of your program.

 Be certain that you do not have any extra space between the < and the iostream.h
file name (Display 2.1) or between the end of the file name and the closing >.
 The compiler include directive is not very smart: It will search for a file name that
starts or ends with a space! The file name will not be found, producing an error that
is quite difficult to find. You should make this error deliberately in a small program,
then compile it. Save the message that your compiler produces so you know what
the error message means the next time you get that error message.
Compiling and Running a C++ Program

Next you will learn what would happen if you run the C++ program show in Display 2.2. But where is
that program and how do you make it run? You write a C++ program using a text editor in the same
way that you write any other document such as a term paper, a love letter, a shopping list, or
whatever. The program is kept in a file just like any other document you prepare using a text editor.

The way that you compile and run a C++ program also depends on the particular system you are
using. When you give the command to compile your program, this will produce a machine-language
translation of your C++ program. This translated version of your program is called the object code
for your program. The object code for your program must be linked (that is, combined) with the
object code for routines (such as input and output routines) that are already written for you. It is
likely that this linking will be done automatically, so you do not need to worry about linking.

DISPLAY 2.2: Sample Program in C++


#include <iostream.h>

void main ()

int a, b, c;

Lecture Note-Cosc1013
cout<<”Enter values of a, b”; Page 17

cin>>a>>b;
Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

In the above program the statement cin>>a>>b; is an input statement and causes the program to
wait for the user to type two numbers. If we key in two values, say 10 and 20 then 10 will be
assigned to a, 20 to b. The operator >> is known as extraction (or) get from operator.

The statement cout<<”The result is:”<<c; is an output statement that causes the string in quotation
marks to be displayed on the screen as it is and then the content of the variable c is displayed . The
operator << is known as insertion (or) put to operator. The identifier cin is pronounced as ‘C in’ and
cout is pronounced as ‘C out’).

TESTING AND DEBUGGING

A mistake in a program is usually called a bug, and the process of eliminating bugs is called
debugging.

Kinds of Program Errors

The compiler will catch certain kinds of mistakes and will write out an error message when it finds a
mistake. It will detect what are called syntax errors, because they are, by and large, violation of the
syntax (that is, the grammar rules) of the programming language, such as omitting a semicolon.

If the compiler discovers that your program contains a syntax error, it will tell you where the error is
likely to be and what kind of error it is likely to be. If the compiler says your program contains a
syntax error, you can be confident that it does. However, the compiler may be incorrect about
either the location or the nature of the error. It does a better job of determining the location of an
error, to within a line or two, than it does of determining the source of the error. This is because the
Lecture Note-Cosc1013 Page 18
Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

compiler is guessing at what you meant to write down and can easily guess wrong. After all, the
compiler cannot read your mind. Error messages subsequent to the first one have a higher
likelihood of being incorrect with respect to either the location or the nature of the error. Again, this
is because the compiler must guess your meaning. If the compiler’s first guess was incorrect, this will
affect its analysis of future mistakes, since the analysis will be based on a false assumption.

If your program contains something that is a direct violation of the syntax rules for your
programming language, the compiler will give you an error message. However, sometimes the
compiler will give you only a warning message, which indicates that you have done something that
is not, technically speaking, a violation of the programming language syntax rules, but that is
unusual enough to indicate a likely mistake. When you get a warning message, the compiler is
saying, “Are you sure you mean this?” At this stage of your development, you should treat every
warning as if it were an error until your instructor approves ignoring the warning.

There are certain kinds of errors that the computer system can detect only when a program is run.
Appropriately enough, these are called run-time errors. Most computer systems will detect certain
run-time errors and output an appropriate error message. Many run-time errors have to do with
numeric calculations. For example, if the computer attempts to divide a number by zero, that is
normally a run-time error. If the compiler approved of your program and the program ran once with
no run-time error messages, this does not guarantee that your program is correct. Remember, the
compiler will only tell you if you wrote a syntactically (that is, grammatically) correct C++ program. It
will not tell you whether the program does what you want it to do. Mistakes in the underlying
algorithm or in translating the algorithm into the C++ language are called logic errors. For example,
if you were to mistakenly use the multiplication sign * instead of the addition sign + in the program
in Display 2.2, that would be a logic error. The program would compile and run normally, but would
give the wrong answer. If the compiler approves of your program and there are no runtime errors,
but the program does not perform properly, then undoubtedly your program contains a logic error.
Logic errors are the hardest kind to diagnose, because the computer gives you no error messages to
help find the error. It cannot reasonably be expected to give any error messages. For all the
computer knows, you may have meant what you wrote.

Quick quiz

1. What are the three main kinds of program errors?

2. What kinds of errors are discovered by the compiler?

Lecture Note-Cosc1013 Page 19


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

3. If you omit a punctuation symbol (such as a semicolon) from a program, an error is produced.
What kind of error?

4. Omitting the final brace} from a program produces an error. What kind of error?

Comments

Comments are notice that added to your program to describe the logic and how the particular part
of the program is work. The comment lines in the program are ignored by the compiler. There are
two types of comments. These are:

Single line comment: C++ introduces single line comment // (double slash). Comments starts with a
double slash symbol and terminate at the end of line.

Example: c=5.0/9*(f-32); //conversion formula.

Multi line comment: Multi line comment symbols are /*, */ .

E.g : /* this is an example of C++ program to illustrate some of its features and how c++ is
written*/

Variable

Variables are often referred to as named memory locations to store a determined value. The value
of a variable may vary throughout program means that, a variable may take different values at
different times during execution. Each variable needs an identifier that distinguishes it from the
others, for example, in the code a=5 the variable identifier is ‘a’, but we could have called the
variables with any names we wanted to invent, as long as they were valid identifiers.

Identifiers
 A valid identifier is a sequence of one or more letters, digits or underscore characters
(_ ).

 The length of an identifier is not limited, although for some compilers only the 32 first characters
of an identifier are significant (the rest are not considered).
 Neither spaces nor marked letters can be part of an identifier.
 Variable identifiers should always begin either with a letter or underscore character
(_ ). They can never begin with a digit. But (_) this is usually reserved for external links.

Lecture Note-Cosc1013 Page 20


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

 Our own identifiers cannot match any key word of the C++ language nor your compiler's specific
ones since they could be confused with these.
 The C++ language is "case sensitive", that means that an identifier written in capital letters is not
equivalent to another one with the same name but written in small letters. Thus, for example the
variable RESULT is not the same as the variable result nor the variable Result.

Some of the keywords supported by ANSI-C++ Standard

asm, auto, bool, break, case, catch, char, class, const,


const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new,
operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try,
typedef, typeid, typename, union, unsigned, using, virtual,
void, volatile, wchar_t , far, huge near, and, and_eq, bitand,
bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Built in 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

Lecture Note-Cosc1013 Page 21


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

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

Integer They are the numbers without decimal part.Ex:69,360,32330.

Float, Double They are the numbers with decimal point. Ex:69.65,3.1415.

Character Any letter enclosed within single quotes comes under character.

The modifiers signed, unsigned, long, and short may be applied to character and integer basic data
types. However, the modifier long may also be applied to double. The following table lists all
combinations of the basic data types and modifiers along with their size and range.

Size & Range of C++ Basic Data Types

Type Bytes* Range*

Char 1 -128 to 127

unsigned char 1 0-255

signed char 1 -128 to 127

Int 2 or 4 -32768 to 32767

unsigned int 2 or 4 0 to 65535

signed int 2 or 4 -32768 to 32767

short int 2 -32768 to 32767

unsigned short 2 0 to 65535


int

signed short int 2 -32768 to 32767

long int 4 -2147483648 to 2147483647

signed long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

Float 4 3.4E -38 to 3.4E +38

Double 8 1.7E -308 to 1.7E +308

Lecture Note-Cosc1013 Page 22


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

long double 10 304E -4932 to 1.1E +4932

* The values of the columns Size and Range depend on the system the program is compiled
for.
Declaration of Variables
 In order to use a variable in C++, we must first declare it specifying the data type.
 The syntax to declare a new variable is to write the data type specifier that we want (like
int, short, float...) followed by a valid variable identifier.
 For example:
 int a;  declares a variable of type int with the identifier a
 float mynumber; declares a variable of type float with the identifier mynumber.
 Once declared, variables a and mynumber can be used within the rest of their scope in the
program.
 To declare several variables of the same type and to save some writing work you can declare
all of them in the same line separating the identifiers with commas.
 E.g: int a, b, c;  declares three variables (a, b and c) of type int.
Initialization of Variables
 When declaring a local variable, its value is undetermined by default.
 To store a concrete value for a variable the moment it is declared append an equal sign
followed by the value wanted to the variable declaration:
o Syntax: type identifier = initial_value ;
o E.g: int a = 0;  Declare an int variable called a that contains the value 0 at the
moment in which it is declared.
 C++ has added a new way to initialize a variable: by enclosing the initial value
between parenthesis ():
o Syntax: type identifier (initial_value) ;
o For example: int a (0);
 Both ways are valid and equivalent in C++.
Scope of variables

 All the variables that we intend to use in a program must have been declared with its type
specifier in an earlier point in the code.
 A variable can be either of global or local scope.
 A global variable is a variable declared in the source code, outside all functions, while a local
variable is one declared within the body of a function or a block.
 Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.
 The scope of local variables is limited to the block enclosed in braces ({}) where they are
declared. For example, if they are declared at the beginning of the body of a function (like in

Lecture Note-Cosc1013 Page 23


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

function main) their scope is between its declaration point and the end of that function. This
means that if another function existed in addition to main, the local variables declared in
main could not be accessed from the other function and vice versa.
Constant

 Constants are expressions with a fixed value.


Literals

 Literals are used to express particular values within the source code of a program. For
example, when we wrote: a = 5 ; the 5 in this piece of code was a literal constant.
 Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean Values.
Integer Numerals

 They are numerical constants that identify integer decimal values.


 C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers
(base 16).
 To express an octal number we have to precede it with a 0 (zero character).
 To express a hexadecimal number we have to precede it with the characters 0x (zero, x).
 E.g: 75 // decimal 0113 // octal 0x4b // hexadecimal . All of these represent the same
number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal
numeral, respectively.
 Literal constants, like variables, are considered to have a specific data type. By default,
integer literals are of type int. We can force them to either be unsigned by appending the u
character to it, or long by appending l.
 E.g: 75 // int 75u // unsigned int 75l // long 75ul // unsigned long
Floating Point Numbers

 They express numbers with decimals and/or exponents. They can include either a decimal
point, an e character (that expresses "by ten at the Xth height", where X is an integer value
that follows the e character), or both a decimal point and an e character.
 In both cases, the suffix can be specified using either upper or lowercase letters.
 For e.g: 3.14159 // 3.14159
6.02e23 // 6.02 x 10^23

1.6e-19 // 1.6 x 10^-19

3.0 // 3.0

 These are four valid numbers with decimals expressed in C++.


 The default type for floating point literals is double.

Lecture Note-Cosc1013 Page 24


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

 To explicitly to express a float or long double numerical literal, we use the f or l suffixes
respectively: 3.14159L // long double 6.02e23f // float
 Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be
written using either lower or uppercase letters without any difference in their meanings.
Boolean literals

 There are only two valid Boolean values: true and false.
 These can be expressed in C++ as values of type bool by using the Boolean literals true and
false.
Character and string literals

 There also exist non-numerical constants, like:


 'z'  Represents a single character.
 "Hello world" Represents strings of characters.
 To represent a single character we enclose it between single quotes (').
 To express a string of more than one character we enclose them between double quotes (").
 x refers to variable x, whereas 'x' refers to the character constant 'x' and “x” represent
string constant.
Escape codes.

 There are special characters that are difficult or impossible to express otherwise in the
source code of a program, like newline (\n) or tab (\t). All of them are preceded by a
backslash (\). Here you have a list of some of such escape codes:
 String literals can extend to more than a single line of code by putting a backslash sign (\) at
the end of each unfinished line. E.g: "string expressed in \ two lines"

Lecture Note-Cosc1013 Page 25


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

Defined constants (#define)

 To define our own names for constants that we use very often without having to resort to
memory consuming variables, simply by using the #define preprocessor directive. Its format
is: #define identifier value
 For example: #define PI 3.14159
 #define NEWLINE '\n'
 This defines two new constants: PI and NEWLINE. Once they are defined, you can use them
in the rest of the code as if they were any other regular constant.
 In fact the only thing that the compiler preprocessor does when it encounters #define
directives is to literally replace any occurrence of their identifier (in the previous example,
these were PI and NEWLINE) by the code to which they have been defined (3.14159 and '\n'
respectively).
 The #define directive is not a C++ statement but a directive for the preprocessor; therefore
it assumes the entire line as the directive and does not require a semicolon (;) at its end.
Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would
do with a variable:

const int PI = 3.14159

const char tab = '\t';

Here, PI and tabulator are two typed constants. They are treated just like regular variables except
that their values cannot be modified after their definition.

Introduction to Strings

 Variables that can store non-numerical values that are longer than one single character are
known as strings.

Lecture Note-Cosc1013 Page 26


Module Title: Basic Programming

Course Title: Fundamentals of Programming I

Compiled By: Destalem H

 The C++ language library provides support for strings through the standard string class. This
is not a fundamental type, but it behaves in a similar way as fundamental types do in its
most basic usage.
 A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code:
<string>
#include <iostream.h>

#include <string.h>

int main ()

string mystring = "This is a string";

cout << mystring;

return 0;

 Both initialization formats are valid with strings:


o string mystring = "This is a string";
o string mystring ("This is a string");
 Strings can also perform all the other basic operations that fundamental data types can, like
being declared without an initial value and being assigned values during execution.
Operators

 An operator is a symbol that tells the computer to perform certain mathematical (or) logical
manipulations.
 Operators are used in programs to manipulate data and variables.
 C++ operators can be classified into number of categories. They include
1. Arithmetic operators. 5. Increment / Decrement operators.
2. Relational operators 6. Conditional operators.
3. Logical operators. 7. Bitwise operators
4. Assignment operators
1. Arithmetic operators: C++ provides all the basic arithmetic operators like add (+), subtract (-), multiply (*),
divide (/), and mod (%).mod gives remainder of division.
Eg.. For mod: if a = 10; b = 3; c = a % b;  c = 1;

Lecture Note-Cosc1013 Page 27


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

2. Relational operators: These are the operators which relate the operands on either side of them like less
than(<),less than or equal(<=),equal(==),Greater than(>),Greater than or equal(>=)and not equal(!=). The
result of a relational operation is a Boolean value that can only be true or false, according to its Boolean
result.
3. Logical operators: C++ has the following three Truth table for AND and OR operations
logical operators. && (meaning logical AND), ||
(logical OR), ! (logical NOT). op-1 op-2 op-1 && op-2 op-1 || op-2
E.g:( (5 == 5) && (3 > 6) )
F F F F
// evaluates to false ( true && false ).
F T F T
((5 == 5) || (3 > 6) )
T F F T
// evaluates to true ( true || false ).
T T T T
4. Assignment operators: used to assign the result of
an expression to a variable and the symbol used is ‘= ‘.
o The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right
one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a
constant, a variable, the result of an operation or any combination of these.
o It is of 3 types:.
(i) Simple assignment E.g: a = 9;
(ii) Multiple assignment E.g: a = b = c = 36; a = 2 + (b = 5);fs
(iii) Compound assignment
E.g: a + = 15; (add 15 to a .Equivalent a =a +15;)

b - = 5; (subtract 5 from b).

c * = 6; (Multiply c by 6).

d / = 5; (divide d by 5 equal to d =d /5; ).


e % = 10; (divide e by 10 & store remainder in e).
5. Auto increment / decrement (+ + / - - ): used to automatically increment and decrement the value of a
variable by 1. There are 2 types of incrementing or decrementing.
a. Prefix auto increment / decrement --- Adds /subtracts 1 to the operand & result is assigned to the
variable on the left.
Eg. : a = 5;
a=5;

Lecture Note- CoSc1012 Page 28


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

b=++a;

b=--a;
Result a=b=6;
a=b=4;
b. Postfix auto increment / decrement --- This first assigns the value to the variable on the left & then
increments/decrements the operand.
Eg. : a = 5;
a=5;
b=a++;

b=a--;
Result b=5, a=6 b=5,a=4;
 Generally a=a+1 can be written as ++a, a++ or a+=1. Similarly a=a-1 can be written as a--, --a or a -= 1.
6. Conditional operator (ternary operator):
 Conditional expressions are of the following form.
exp1 ? exp2 : exp3 ;

 exp1 is evaluated first. If the result is true then exp2 is evaluated else exp3 is evaluated. It is
this evaluated value that becomes the value of the expression.
 For example, consider the following statements. a=10; b=15; x = (a>b) ? a : b; In this example
x will be assigned the value of b.
7. Bitwise Operators
 Bitwise operators modify variables considering the bit patterns that represent the values
they store.
 & Bitwise AND
 | Bitwise Inclusive OR
 ~ Unary complement (bit inversion)
Type conversion in Assignments

 The value of the right side (expression side) of the assignment is converted to the type of the left
side (target variable).
 E.g: int x; char ch; float f;
ch=x;  appropriate amount of high order bits are removed.

x=f;  x will receive the non fractional part of f.

f=ch; 8-bit integer value of ch is stored as the same in floating point format.

f=x; convert an integer value into floating point format.

Lecture Note- CoSc1012 Page 29


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

Explicit type casting


 Type casting operators allow converting a datum of a given type to another. There are several
ways to do this in C++.
 The simplest one, is to precede the expression to be converted by the new type enclosed
between parentheses (()):
 E.g: int i;
float f = 3.14;

i = (int) f;

o Code converts the float number 3.14 to an integer value (3), the remainder is lost. Here,
the typecasting operator was (int).
 Another way to do the same thing in C++ is using the functional notation:
 Preceding the expression to be converted by the type and enclosing the expression between
parentheses: E.g: i = int ( f );
 Both ways of type casting are valid in C++.
sizeof()

 This operator accepts one parameter, which can be either a type or a variable itself and returns
the size in bytes of that type or object:
a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type.

 The value returned by sizeof is a constant, so it is always determined before program


execution.
Priority of operators
 When making complex expressions with several operands, we may have some doubts about which
operand is evaluated first and which later.
o For example, in this expression: a = 5 + 7 % 2. we may doubt if it really means:
 a = 5 + (7 % 2) with result 6, OR
 a = (5 + 7) % 2 with result 0
o The correct answer is the first of the two expressions, with a result of 6. There is an
established order with the priority of each operator, and not only the arithmetic ones (those
whose preference we may already know from mathematics) but for all the operators which
can appear in C++.
 Also in the case that there are several operators of the same priority level- which one
must be evaluated first, the rightmost one or the leftmost one is decided by the
Associativity of the operator.
 All these precedence levels for operators can be manipulated or become more legible
using parenthesis signs ( and ), as in this example: a = 5 + 7 % 2; might be written as: a = 5
+ (7 % 2); or a = (5 + 7) % 2;according to the operation that we wanted to perform.

Lecture Note- CoSc1012 Page 30


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

 From greatest to lowest priority, the priority order is as follows:


Priority Operator Description Associativity

1 :: Scope Left

2 () [ ] -> . sizeof Left

3 ++ -- increment/decrement Right

~ Complement to one (bitwise)

! unary NOT

&* Reference and Dereference (pointers)

(type) Type casting

4 */% arithmetical operations Left

5 +- arithmetical operations Left

6 << >> bit shifting (bitwise) Left

7 < <= > >= Relational operators Left

8 == != Relational operators Left

9 &^| Bitwise operators Left

10 && || Logic operators Left

11 ?: Conditional Right

= += -= *= /= %=
12 Assignation Right
>>= <<= &= ^= |=

13 , Comma, Separator Left

(The operators that you are familiar with are shaded in the above table)

Input/Output

Lecture Note- CoSc1012 Page 31


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

 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. We do
not really need to care about many specifications about the physical media associated with the
stream.
 The insertion operator (<<) may be used more than once in a single statement:
o cout << "Hello, " << "I am " << "a C++ statement";
o cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
o 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
 cout does not add a line break after its output unless we explicitly indicate it.
 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):
o E.g: cout << "First sentence.\n ";
o cout << "Second sentence.\nThird sentence.";
 Additionally, to add a new-line, you may also use the endl manipulator.
o Eg: cout << "First sentence." << endl;
o cout << "Second sentence." << endl;
 cin can only process the input from the keyboard once the RETURN key has been pressed.
Therefore, even if we request a single character, the extraction from cin will not process the input
until the user presses RETURN after the character has been introduced.
 Also cin extraction stops reading as soon as if finds any blank space character, so in this case we
will be able to get just one word for each extraction.
Library Functions

 C+ + consists of many library functions which contain the functions that are used in the program
construction of the language.
 These are the header files that are to be included before main () & are sometimes termed as
preprocessor statements.
 Here are some files given:
Header File Purpose of including in the Program

iostream.h Standard input /output streams like cin, cout etc.

math.h Mathematical functions like sin(), cos(), sqrt(),log() etc.

stdlib.h Standard library functions like conversion of one type to other etc.

string.h String manipulation functions like strcpy (), strcat(), strcmp() etc.

Lecture Note- CoSc1012 Page 32


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

ctype.h Declares functions for testing characters.

E.g: isalpha(),isnum(),islower(),toupper(),tolower() etc.

time.h Includes date & time functions.

Sample program 1: Write a c++ program to calculate area of a circle for given diameter d, using formula
r2 where r=d/2.

// To calculate area of circle

#include<iostream.h>

void main()

float A, pi=3.1415;

float d, r;

cout<<”Enter the diameter of the circle\n”;

cin>>d;

r=d / 2;

A= pi * r * r;

Cout<< “\nArea of circle = ”<<A;

Sample program 2: Write a c++ program to read the temperature in Fahrenheit and convert it into Celsius.
(Formula: c= (5.0/9)*(f-32)).

#include<iostream.h>

void main ()

float c,f;

cout<<”Enter the temperature in Fahrenheit:”;

cin>>f;

c=(5.0 / 9)*(f - 32);

Lecture Note- CoSc1012 Page 33


Module: Basic Programming

Course: Fundamentals of Programming

Compiled By: Destalem H.

cout<<”The temperature in Celsius is: ”<<c;

Lecture Note- CoSc1012 Page 34

You might also like