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

chapter2

Uploaded by

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

chapter2

Uploaded by

Daniel Getachew
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter 2

C++ programming basics


Compilers take source code (.CPP extension) and transform it into executable files (.EXE
extension), which your computer can run.

Higher Lower level


level language
language,
Compiler (machine
C++ code)

Basic program construction


Let’s first look at a very simple C++ program. It simply prints a sentence on the screen. Here
it is:
#include <iostream>
using namespace std;
int main()
{
cout << “wollo university\n”;
return 0;
}
Always start with main function, main ()
Program execution always starts from the main function. Program may consist of many
functions but when program execution starts control goes to the main function (main ())
The parentheses following the word main are the distinguishing feature of a function.
Without the parentheses the compiler would think that main refers to a variable or to some
other program element. So if there is no main function in your program error will be
reported by the compiler.
The word int preceding the function name indicates that this particular function has a return
value of type int.
Braces {and}
Every function must use pair of braces around function body. Inside function body above are
program statements.
Program statements
Program statements are instructions to the computer to do something. In the above
program there are two program statements
Statement 1: cout<<”wollo university\n”; this statement tells the computer to display the
quoted phrase on monitor.
Statement 2: return statement, return 0; this tells main function to return the value 0 to
whoever called the function, in this case the operating system or compiler. The program
statement is terminated by semicolon. So semicolon signals end of program statement.
White space
White space is defined as spaces, carriage returns, line-feeds, tabs, vertical tabs, and form
feeds. Actually, the compiler ignores white space almost completely. These characters are
invisible to the compiler. You can put several statements on one line, separated by any
number of spaces or tabs, or you can run your program statement over two or more lines. It
is all the same to the compiler. So the above program can be written in the following way:
#include <iostream>
using
namespace std;
int main ()
{ cout
<<“Every age has a language of its own\n”
; return0 ;
}
This syntax is not recommended, it is nonstandard and hard to read but it can be compiled
correctly.
Exceptions to the rule that white space is invisible to the compiler
 Preprocessor directive must be written on one line
 String constants, such as Wollo University in the above program, can not be broken
into separate lines. If you need a long string constant, you can divide the string into
two separate strings, each surrounded by quotes.
Output using cout
As explained earlier, the statement cout << “wollo university\n”; causes the phrase in
quotation marks to be displayed on the screen. How does this work? The identifier cout
(pronounced C out) is actually an object. It is predefined in C++ to correspond to the
standard output stream and the standard output stream normally flows to screen device
The operator << is called the insertion or put to operator. It directs the contents of the
variable right after the insertion operator to cout. For example in the above program, it
directs the string constant wollo university to cout, which sends it to the display.

Fig 1 output with cout


String constants
The phrase in quotation marks, “wollo university\n”, is an example of a string constant. A
string constant, unlike a variable, cannot be given a new value as the program runs. Its value
is set when the program is written, and it retains this value throughout the programs
existence.
Escape sequence
The character \n at the end of string constant is an example of escape sequence. It causes
the next text output to be displayed on new line. Common escape sequences usually used in
C++ are the following
Escape sequence Character
\n new line
\t Tab
\r Return
Preprocessor directives
Recall that program statements are instructions to the computer to do something, such as
adding two numbers or printing a sentence. A Preprocessor directive, on the other hand, is
an instruction to the compiler. The preprocessor directive #include tells the compiler to
insert another file into your source file before it begins real compilation process. In effect,
the #include directive is replaced by the contents of the file indicated. Using a #include
directive to insert another file into your source file is similar to pasting a block of text into a
document with your word processor. The #include is only one of many preprocessor
directives, all of which can be identified by the initial # sign. The type of file usually included
by # include is called header file.
Header file
In the above program the preprocessor directive, #include, tells the compiler to add the file
iostream to your source file before compiling. Here iostream is an example of a header file
(sometimes called an include file). It is concerned with basic input/output operations, and
contains declarations that are needed by the cout identifier and the << operator. Without
these declarations, the compiler wont recognize cout and will think << is being used
incorrectly.
Note:
The newer Standard C++ header files don’t have a file extension, but some older header
files, left over from the days of the C language, have the extension .h.
The using directive
The C++ program can be divided into different namespaces. A namespace is a part of the
program in which certain names are recognized; outside of the namespace they are
unknown. The directive, using namespace std, says that all the program statements that
follow are within the std namespace. Various program components such as cout are
declared within this namespace. Namespaces are used to partition global namespace; this
eliminates or at least reduces name conflicts.
Program comments
Comments are an important part of any program. They help the person writing a program,
and anyone else who must read the source file, understand what is going on. The compiler
ignores comments, so they are not a part of exe file
Syntax: Comments start with a double slash symbol (//) and terminate at the end of the
line. A comment can start at the beginning of the line or on the same line following a
program statement.
Example: // C++ programming basics
Alternative syntax (for multiple lines of comment)
Begins with /* character pair and ends with */
Example /* this program is about
Basics of C++ program
Usually used in developing
Application */
Data types and Variables
Data types define the way you use storage (memory) in the programs you write. By
specifying the data type you tell the compiler how to create a particular piece of storage and
also how to manipulate the storage.

Variables
It is a named location in memory that is used to hold a value or data. So variables are
located in particular places in the computer’s memory. When a variable is given a value, that
value is actually placed in the memory space assigned to the variable.
Syntax: < type> < variable name>;
Example: int number;

Variable names
For naming variables you can use upper and lowercase letters, digits or underscore (_)
character. The first character must be a letter or underscore.
 C++ keywords (predefined words)can’t be used as a variable name Example : int
const ; is wrong declaration because const is a keyword in c++
 Compliers distinguish between upper and lower case letters
Example: int num;
int Num ; here num and Num are treated as separate variable names and
will be allocated separate memory location.

Input with cin


Syntax: cin>> variable name;
Example : cin>>x; where x is variable name
The keyword cin (pronounced C in) is an object, predefined in C++ to correspond to the
standard input stream. This stream represents data coming from the keyboard. The >> is the
extraction or get from operator. It takes the value from the stream object on its left and
places it in the variable on its right.

Fig input using cin


Example:
Write a C++ program that accepts two integer numbers from the user and prints the sum of
input numbers on the screen
# include<iostream>
using namespace std;
int main()
{ // variable declaration.
int num1,num2;
// ask user for input
cout<<”enter the numbers\n”;
// accept input
cin>>num1>>num2;
// process data
num1=num1+num2;
// display sum
cout<<”the sum of numbers:\n”;
cout<<num1;
return 0;
}
Exercise:
Write C++ program that invites the user to enter the radius of circle and display the area of
circle on the monitor.
Operators
1. arithmetic operators
Involves +,-,*, /, %. Their operations are analogues to their use in linear algebra
Remainder operator (%): finds the remainder when one number is divided by another
Example: 6%8=6 19%8= 3
8%8=0 10%8=2
2. increment/decrement operator
Example: ++ count;
Count++;
Prefix…..operand precedes the variable
Postfix……operand follows the variable
Example: total_weight=total_weight*++count;

Count will be incremented first before multiplication but if we had use postfix
notation (count++) multiplication will be performed first and then count will be
incremented
Example (for decrement case)
--count;
Count--;
It has the same definition as before except here the value reduces by one.
Example
What is the output of the following program?
#include<iostream>
using namespace std;
int main()
{
int count=10;
cout<<”count=”<<count<<endl;
cout<<”count=”<<++count<<endl;
cout<<”count=”<<count<<endl;
cout<<”count=”<<count++<<endl;
cout<<”count=”<<count<<endl;
return 0;
}
Exercise on chapter two
1. If you have two fractions, a/b and c/d their sum can be obtained from the formula
a c a*d + b*c
--- + --- = -----------
b d b*d
For example; 1/4 plus 2/3 is
1 2 1*3 + 4*2 3 + 8 11
--- + --- = ----------- = ------- = ----
4 3 4*3 12 12
Write a program that encourages the user to enter two fractions, and then displays their
sum in fractional form. (You don’t need to reduce it to lowest terms.) The interaction of
program with the user might look like this:
Enter first fraction: 1/2
Enter second fraction: 2/5
Sum = 9/10
2. You can convert temperature from degrees Celsius to degrees Fahrenheit by multiplying
by 9/5 and adding 32. Write a program that allows the user to enter a floating-point number
representing degrees Celsius, and then displays the corresponding degrees in Fahrenheit.

You might also like