Cs 103 Computer System and Programming: Chapter 02: C++ Programming Basics

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

CS 103 COMPUTER SYSTEM

AND PROGRAMMING
CHAPTER 02: C++ PROGRAMMING BASICS

D E PA R T M E N T O F C I V I L E N G I N E E R I N G , FA C U LT Y O F
E N G I N E E R I N G A N D T E C H N O L O G Y,
I N T E R N AT I O N A L I S L A M I C U N I V E R S I T Y H - 1 0 , I S L A M A B A D ,
PA K I S TA N
H T T P : / / W W W. I I U . E D U . P K
CS 103 COMPUTER SYSTEM AND
PROGRAMMING
Course Code CS103
Course Title Computer System & Programming
Credit Hours 1+2
Contact Hr 1+6
Pre-Requisite None
Text Books Introduction to Matlab for Engineers.
Reference Books Object Oriented Programming by Robert Lafore
Let Us C++ by Yashwant Kanetkar
Objective of Course Objective of Course
To develop skills of computer programming and its applications in
elementary civil engineering problems
Course Outline Programming for Civil Engineers:
Objective of this course is to learn basics of
programming and its application to Civil
Engineering. Programming Language can be C++,
SCILAB Scripting, MATLAB Scripting or VB.NET.
Variables, Constant, Control Structures, Loop,
Functions, Sub Procedure, Plotting, Matrix
Operation, Solving System of linear Equations,
Arithmetic Calculator, Solving Simple Numerical
Problem of Engineering and Mathematical
Subjects, Solving Calculus, Differential and Integral
CS 103 COMPUTER SYSTEM AND PROGRAMMING

Marks Distribution of
CSP (Theory)

Quizes 10%

Assignments 05%

Sessional 1 20%

Sessional 2 15%

Terminal Exam 50%


CS 103 COMPUTER SYSTEM AND PROGRAMMING

Marks Distribution of
CSP Lab

Lab Tasks 15 %

Lab Attendance 10%

Mid Term Exam 20%

Semester Project 25%

Terminal Exam 30%


BASIC C++ PROGRAM CONSTRUCTION
1 //first.cpp
2 #include <iostream>
3 using namespace std;
4 int main()
5 {
6 cout << "Welcome to this course\n";
7 system("PAUSE");
8 return 0;
9 }

Explanation:
 This program consists of a single function
called main().
BASIC PROGRAM CONSTRUCTION
 Because of the parentheses() the compiler
comes to know that this a function not a
variable.
 The parentheses aren’t always empty. They’re
used to hold function arguments (values passed
from the calling program to the function).
 Line number 2 and 3 are not part of the
function.
 The word int preceding the function name
indicates that this particular function has a
return value of type int.
 The body of a function is surrounded by braces
(sometimes called curly brackets).
BASIC PROGRAM CONSTRUCTION
 Every function must use this pair of braces
around the function body.
 A function body can consist of many statements
but this function has only three statements
(line number 5, 6 and 7)
 You can put several statements on one line and
one statement in over two or more lines.
1 cout
2 <<“Welcome to this course\n”
3 ;

1 cout <<“Welcome Students\n” ; return 0;


BASIC PROGRAM CONSTRUCTION
 We don’t recommend these syntax. it’s
nonstandard and hard to read. but it does
compile correctly.
 #include is a preprocessor directive, which
must be written on one line.
 A string constant “Welcome to this course\n”
can also be broken into separate lines if u
insert a backslash (\) at the line break or
 divide the string into two separate strings,
each surrounded by quotes
cout cout
<<“Welcome \ <<“Welcome “
to this \ “to this “
course\n” “course\n”
; ;
BASIC PROGRAM CONSTRUCTION
 We don’t recommend these syntax. it’s
nonstandard and hard to read. but it does
compile correctly.
 #include is a preprocessor directive, which
must be written on one line.
 A string constant “Welcome to this course\n”
can also be broken into separate lines.e.g.
 A programs may consists of many functions but
the main() function will be executed first.
 If there is no function called main() in your
program, an error will be reported when you
run the program.
 main() function may also call other functions.
PROGRAM STATEMENTS
 There are two statements this program
cout <<“Welcome to this course\n”;
return 0;
 The first statement tells the computer to
display the quoted phrase.
 A semicolon ; signals the end of the
statement. If you leave out the semicolon, the
compiler will often signal an error.
 The return 0; tells main() to return the value
0 to whoever called it, in this case the
operating system or compiler.
 you can not give main() the return type of
void, this is an error in new compilers.
OUTPUT USING COUT
cout <<“Welcome to this course\n”;
 The identifier cout (pronounced “C out”) is
actually an object. It is predefined in C++ to
correspond to the standard output stream.
 A stream is an abstraction that refers to a
flow of data. The standard output stream
normally flows to the screen display although
it can be redirected to other output devices.
 The operator << is called the insertion or put
to operator. It directs the contents of the
variable on its right to the object on its
left.
 In our program it directs the string constant
<<“Welcome to this course\n” to cout, which
sends it to the display.
OUTPUT USING COUT

 (If you know C, you’ll recognize << as the


left-shift bit-wise operator and wonder how it
can also be used to direct output.
 In C++, operators can be overloaded. That is,
they can perform different activities,
depending on the context.
STRING CONSTANTS
 The phrase in quotation marks, “Welcome to
this course\n”, is an example of a string
constant.
 A 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 program’s
existence.
 The ‘\n’ character at the end of the string
constant is an example of an escape sequence.
 The ‘\n’ causes the next text output to be
displayed on a new line.
 Line no. 2 and 3 in our program are called
directives. The first is a preprocessor
directive,and the second is a using directive.
DIRECTIVES
 They’re not part of the basic C++ language,
but they’re necessary anyway.
Preprocessor Directives
#include <iostream>
 This is not a program statement or a part of a
function body. It starts with a number sign
(#). It’s called a preprocessor directive.
 Recall that program statements are instruct-
ions 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. A part of
the compiler called the preprocessor deals
with these directives before it begins the
real compilation process.
#INCLUDE DIRECTIVE
 The preprocessor directive #include tells the
compiler to insert another file into your
source file. In effect, the #include directive
is replaced by the contents of the file
indicated.
 Using an #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.
 #include is only one of many preprocessor
directives, all of which can be identified by
the initial # sign.
 The type file usually included by #include is
called a header file.
HEADER FILES
 In our program the preprocessor directive
#include tells the compiler to add the source
file IOSTREAM to the FIRST.CPP source file
before compiling.
 IOSTREAM is an example of a header file
(sometimes called an include file). It’s
concerned with basic input/output operations,
and contains declarations that are needed by
the cout identifier and the << operator.
 Without these declarations, the compiler won’t
recognize cout and will think << is being used
 incorrectly.
 The newer Standard C++ header files don’t have
a file extension, but some older header files
have the extension .H.
USING DIRECTIVE
 A 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’re 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. If we didn’t
use the using directive, we would need to add
the std name to many program elements.e.g.
std::cout << “Welcome to this course\n”;
 To avoid adding std:: dozens of times in
programs we use the using directive instead.
COMMENTS
 Comments help the person writing a program,
and anyone else who must read the source file,
understand what’s going on.
 The compiler ignores comments, so they do not
add to the file size or execution time of the
executable program.
 Comments start with a double slash symbol (//)
and terminate at the end of the line
1 //first.cpp
2 #include <iostream> //preprocessor directive
3 using namespace std; //”using” directive
4 int main() //function name “main”
5 { //start function body
6 cout <<“Welcome to this course\n”; //statement
7 return 0; //statement
8 } //end of function body
OTHER STYLES OF COMMENTS
1 /* this is an old-style comment */
2
3 /* this
4 is a
5 potentially
6 very long
7 multiline
8 comment
9 */
10
11
12 int main(/* a comment within parentheses*/)
13
14 { /* this is comment into the function body */ }
15
16
INTEGER VARIABLE
 Variables are the most fundamental part of any
language. A variable has a symbolic name and
can be given a variety of values.
 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.
 Integer variables represent integer numbers
like 1, 30,000, and –27. Such numbers are used
for counting discrete numbers of objects, like
11 pencils or 99 bottles of beer.
 integers have no fractional part; you can
express the idea of four using integers, but
not four and one-half.
DEFINING AN INTEGER VARIABLE
 Integer variables exist in several sizes, but
the most commonly used is type int.
 The amount of memory occupied by the integer
types is system dependent.
 On a 32-bit system such as Windows, an int
occupies 4 bytes (which is 32 bits) of memory.
This allows an int to hold numbers in the
range from –2,147,483,648 to 2,147,483,647.
 The type int occupies 4 bytes on current
Windows computers, it occupied only 2 bytes in
MS-DOS and earlier versions of Windows.
 Figure: A variable of type int in memory
DEFINING AN INTEGER VARIABLE
// intvars.cpp
// demonstrates integer variables
#include <iostream>
using namespace std;
int main(){
int var1; //define var1
int var2; //define var2
var1 = 20; //assign value to var1
var2 = var1 + 10; //assign value tovar2
cout << "var1+10 is ";//output text
cout << var2 << endl; //output value of var2
system("PAUSE"); return 0;
}
CODE EXPLANATION
 The statements int var1; int var2; define two
variables, var1 and var2 of type integer.
 These statements, which are called
declarations, must terminate with a semicolon
 You must declare a variable before using it.
However, you can place variable declarations
anywhere in a program. It’s not necessary to
declare variables before the first executable
statement (as was necessary in C).
 A declaration introduces a variable’s name
(such as var1) into a program and specifies
its type (such as int).
 if a declaration also sets aside memory for
the variable, it is also called a definition.
VARIABLE NAMES
 The statements int var1; int var2; in the
program are definitions, as well as declara-
tions, because they set aside memory for var1
and var2.
 The program uses variables named var1 and var2
 The names given to variables are called
identifiers. You can use upper and lowercase
letters, and the digits from 1 to 9. You can
also use the underscore (_).
 The first character must be a letter or
underscore. Identifiers can be as long as you
like, but most compilers will only recognize
the first few hundred characters. The compiler
distinguishes between upper- and lowercase
letters, so Var is not the same as var or VAR.
KEYWORD
 You can’t use a C++ keyword as a variable
name. A keyword is a predefined word with a
special meaning. int, class, if, and while are
examples of keywords. A complete list of
keywords can be found in Appendix B.
 A variable’s name should make clear to anyone
reading the listing variable’s purpose and how
it is used. Thus a variable int age is better
than something simple like int a or int aa.
 The statements var1 = 20; var2 = var1 + 10;
assign values to the two variables.
 The equal sign (=), causes the value on the
right to be assigned to the variable on the
left. in the statement var1 = 20; var1, which
had no value, is given the value 20.
INTEGER CONSTANT
 The number 20 is an integer constant.Constants
don’t change during the course of the program.
 An integer constant consists of numerical
digits. There must be no decimal point in an
integer constant, and it must lie within the
range of integers.
 In the second program line, the plus sign (+)
adds the value of var1 and 10, in which 10 is
another constant. The result of this addition
is then assigned to var2.
 The statement cout << “var1+10 is “; displays
a string constant.
 The next statement cout << var2 << endl;
displays the value of the variable var2.
COUT <<
 cout and the << operator know how to treat an
integer and a string differently.
 If we send them a string, they print it as
text. If we send them an integer, they print
it as a number.
 As you can see, the output of the two cout
statements appears on the same line on the
output screen. No linefeed is inserted
automatically. If you want to start on a new
line, you must insert a linefeed yourself.
 We’ve seen how to do this with the ‘\n’ escape
sequence. Now we’ll see another way: using
something called a manipulator.
THE ENDL MANIPULATOR
 The last cout statement in the INTVARS program
ends with an unfamiliar word: endl. This
causes a linefeed to be inserted into the
stream, so that subsequent text is displayed
on the next line.
 It has the same effect as sending the ‘\n’
character, but is somewhat clearer.
 It’s an example of a manipulator. Manipulators
are instructions to the output stream that
modify the output in various ways; we’ll see
more of them as we go along. Strictly
speaking, endl (unlike ‘\n’) also causes the
output buffer to be flushed, but this happens
invisibly so for most purposes the two are
equivalent.
C++ DATA TYPES
Data Type Size Range
bool 1 byte true(1) or false(0)
(signed)char 1 byte (-27)~(+27-1) = -128 ~ +127
unsigned char 1 byte 0 ~ 28-1 = 0 to 255 or
256 Different ASCII Characters
short 2 bytes (-215)~(+215-1) =
(short int) -32,768 ~ +32,767
unsigned short 2 bytes 0 ~ 216-1 = 0 to 65,536
int 4 bytes (-231)~(+231-1) =
(signed int) -2147483648 ~ +2147483647
unsigned int 4 bytes 0 ~ (232-1) =
0 ~ 4,29,49,67,296
long 4 bytes (-231)~(+231-1) =
(long int) -2147483648 ~ +2147483647
C++ DATA TYPES
Data Type Size Range
unsigned 4 bytes 0 ~ 4,29,49,67,296
long
float 4 bytes ±(1.2 × 10-38 ~ 3.4 × 1038)
double 8 byte +(2.2 × 10-308 ~ 1.7 × 10308)
-(2.3 × 10-308 ~ 1.7 × 10308)

 specifying type long will guarantee a four-bit


integer type on a 16-bit system such as MS-DOS
 In 16-bit systems, type int has the same range
as type short.
 On all systems type short occupies two bytes.
C++ DATA TYPES
long v1 = 7678L; // assigns long constant
// 7678 to v1 of type long
 Many compilers offer integer types that
explicitly specify the number of bits used.
 They are __int8, __int16, __int32, and __int64
 char data type is used to store numbers that
confine themselves to a limited range, but it
is commonly used to store ASCII characters.
 ASCII character set is a way of representing
English alphabet in a 8-bit space.
 Character constants use single quotation marks
around a character, like ‘a’ and ‘b’. (Note
that this differs from string constants, which
use double quotation marks)
C++ DATA TYPES
 When the C++
compiler
encounters such a
character
constant, it
translates it into
the corresponding
ASCII code.
 The constant ‘a’
appearing in a
program, for
example, will be
translated into
97, as shown in
Figure.
PROGRAMMING EXAMPLE
// charvars.cpp
// demonstrates character variables
#include <iostream> //for cout, etc.
using namespace std;
int main()
{
char charvar1 = 'A'; // char charvar1 = 65;
char charvar2 = '\t'; // char charvar2 = 9;
cout << charvar1; //display character
cout << charvar2; //display character
charvar1 = 'B'; //char charvar1 = 66;
cout <<charvar1; //display character
cout << '\n'; // cout << char (10);
system("PAUSE"); return 0;
}
ESCAPE SEQUENCE
'\t' and '\n', are special character with have
different behavior. These are called escape
sequence. The name reflects the fact that the
backslash causes an “escape” from the normal way
characters are interpreted.
In this case the t is interpreted not as the
character 't' but as the tab character. A tab
causes printing to continue at the next tab
stop.
cout << "\"Run, \tForrest, run,\" she
said.";
ESCAPE SEQUENCE
This translates to
"Run, Forrest, run," she said.
Sometimes you need to represent a character
constant that doesn’t appear on the keyboard,
such as the graphics characters above ASCII code
127.
To do this, you can use the '\xdd' representa-
tion, where each d stands for a hexadecimal
digit. If you want to print a solid rectangle,
for example, you’ll find such a character listed
as decimal number 178, which is hexadecimal
number B2 in the ASCII table.
cout <<'\x01'; cout<<char(1); //
prints ☺
cout <<'\a'; cout<<char(7); // calls
bell
cout << int('\a'); //
Prints 7
ASCII TABLE
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
unsigned char ch;
for(ch=0 ; ch<255 ; ch++)
cout << int(ch) << "="
<< ch << "\n" ;
getch();
return 0;
}
INPUT WITH CIN
#include <iostream> //for cout, etc.
#include <conio.h>
using namespace std;
int main(){
int A,B,AVG; // run again for float data type
cout << "Enter Value of A :";
cin >> A;
cout << "Enter Value of B :";
cin >> B;
cout<<" You told A = "<< A <<" and B = "<< B <<endl;
AVG = (A+B)/2;
cout <<"and their Average = "<< AVG << endl;
cout<<"\n <Thank U> \n";
getch();
return 0;
}
INPUT WITH CIN
The statement cin >> ftemp; causes the program to wait for
the user to type in a number.
The resulting number is placed in the variable ftemp. 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 (unless
it has been redirected).
echo 100 | first.exe (type in DOS)
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.
INPUT WITH CIN
insertion operator << cab be used repeatedly in the
cout statement. This is perfectly legal
extraction operator >> can be used repeatedly with
cin, allowing user to enter a series of values.
Any arrangement of variables, constants, and
operators that specifies a computation is called an
expression, Thus, alpha+12 and (alpha-37)*beta/2 are
expressions.
Statements tell the compiler to do something and
terminate with a semicolon, while expressions specify
a computation.
There can be several expressions in a statement.
If both *(multiply) and -(subtract) are present in an
expression then the multiplication would be carried
out first, since * has higher priority Than –
* and / have the same precedence. the one on the left
is executed first
FLOATING POINT TYPES
They have both an integer part, to the left
of the decimal point, and a fractional part,
to the right.
Floating-point variables represent what
mathematicians call real numbers, which are
used for measurable quantities such as
distance, area, and temperature. They
typically have a fractional part.
There are two kinds of floating-point
variables in C++: float, double.
float data type occupies 4 bytes (32bits) in
memory while double occupies 8 bytes of
memory.
FLOAT EXAMPLE
// circarea.cpp
// demonstrates floating point variables
#include <iostream> //for cout, etc.
using namespace std;
int main()
{
float rad; //variable of type float
const float PI = 3.14159F; // type const float
cout << "Enter radius of circle: "; // prompt
cin >> rad; // get radius
float area = PI * rad * rad; // find area
cout << "Area is " << area << endl; // display answer
system("PAUSE"); return 0;
}
CODE EXPLANATION
The number 3.14159F is an example of a floating-
point constant.
The decimal point signals that it is a floating-
point constant, and not an integer.
The F specifies that it’s type float, rather
than double or long double.
The number is written in normal decimal
notation.
With type long double, use the letter L.
You can also write floating-point constants
using exponential notation e.g. 1234.56 would be
written 1.23456E3.
The keyword const (for constant) specifies that
the value of a variable will not change
throughout the program.
QUADRATIC EQUATION: Y = X2-6X-7
FLOAT EXAMPLE: QUADRATIC
EQUATION
// A program to calculate Y = X2-6X-7
#include <iostream> //for cout, etc.
using namespace std;
int main(){
float X,Y; //variable of type float
cout << "Enter The Value of X: "; // prompt
cin >> X; // get value of x
Y = (X*X)-(6*X)-7; // find y
// display answer
cout << "For X = “ << X << ",Y = “ << Y << endl;
system("PAUSE");
return 0;
}
CALCULATING ROOTS OF QUADRATIC
EQUATION
// Calculating Roots
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int main(){
double a,b,c,x1,x2; // variable of type float
cout <<" Y = a(X^2) + bX + c \n";
cout<<" Enter The Value of a, b and c: ";
cin >> a >> b >> c; // get first a then b & c
cout << "a=" << a << ", b=" << b << " ,c=" << c << endl;
x1 = (-b+sqrt((b*b-4*a*c)))/(2*a);
x2 = (-b-sqrt((b*b-4*a*c)))/(2*a);
cout << "Roots are x1=" << x1
<< ", x2=" << x2 << endl; // display answer
getch();
return 0;
}
THE SETW() MANIPULATOR
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
long pop1=2425785, pop2=47, pop3=9761;
cout << "LOCATION " << "POP." << endl
<< "Portcity " << pop1 << endl
<< "Hightown " << pop2 << endl
<< "Lowville " << pop3 << endl;
getch();
return 0;
}
THE SETW() MANIPULATOR
#include <iostream>
#include <iomanip> // for setw
#include <conio.h>
using namespace std;
int main(){
long pop1=2425785, pop2=47, pop3=9761;
cout << setw(8) << "LOCATION"
<< setw(12) << "POPULATION" << endl
<< setw(8) << "Portcity" << setw(12) << pop1 << endl
<< setw(8) << "Hightown" << setw(12) << pop2 << endl
<< setw(8) << "Lowville" << setw(12) << pop3 << endl;
getch();
return 0;
}
THE SETW() MANIPULATOR
The setw manipulator causes the number (or string)
that follows it in the stream to be printed within a
field n characters wide, where n is the argument to
setw(n).
The value is right justified within the field.
THE REMAINDER OPERATOR (%)
// remaind.cpp demonstrates remainder operator
#include <iostream>
using namespace std;
int main(){
cout << 6 % 8 << endl // 6
<< 7 % 8 << endl // 7
<< 8 % 8 << endl // 0
<< 9 % 8 << endl // 1
<< 10 % 8 << endl // 2
<< -2 % 8 << endl // -2
<<-13 % 8 << endl; // -5
system("PAUSE");
return 0;
}
ARITHMETIC ASSIGNMENT OPERATORS, += , -= , *= , /= ,
%=
// demonstrates arithmetic assignment operators
#include <iostream>
using namespace std;
int main(){
int ans = 27;
ans += 10; //same as: ans = ans + 10;
cout << ans << ", ";
ans -= 7; //same as: ans = ans - 7;
cout << ans << ", ";
ans *= 2; //same as: ans = ans * 2;
cout << ans << ", ";
ans /= 3; //same as: ans = ans / 3;
cout << ans << ", ";
ans %= 3; //same as: ans = ans % 3;
cout << ans << endl;
system("PAUSE"); return 0;
} // output is : 37, 30, 60, 20, 2
INCREMENT OPERATORS, ++ , --
// increm.cpp demonstrates the increment operator

#include <iostream>
using namespace std;
int main(){
int count = 10;
cout << "count=" << count << endl; // displays 10

//First increment then use this variable


cout << "count=" << ++count <<endl; // displays 11(prefix)
cout << "count=" << count << endl; // displays 11

//First use this variable then increment


cout<< "count=" << count++ <<endl; // displays 11(postfix)
cout << "count=" << count << endl; // displays 12
system("PAUSE"); return 0;
}
ASSIGNMENT #1
(TO BE SUBMITTED ON 11-03-2015)
1. What is the correct variable type for storing the following data:
 The number of pages in your text book
 The cost of this book
 The age of a person
 The number of people in the world
2. Write a program that calculates and prints sum, difference and
product of two numbers. Also, use this program to calculate
remainder and quotient in division of these numbers. Display the
output on the screen.
3. Write a program that gets 6 integers from the user and displays
the sum, average and product of these numbers on screen.
4. Write a Program that input the Temperature from the user in
Fahrenheit Scale and gives the result in Celsius and Kelvin
Scales.

You might also like