Introduction to Programming
Dr. Abdul Haseeb
Books
• Object-Oriented Programming in C++
– Robert Lafore
• C++ how to program
– Paul J. Deitel, Harvey M. Deitel
Introduction to Programming
Why Programming?
• To develop Software
– Application Software
• Word processors, spread sheets, presentation managers
• Video games
– System Software
• Programs that support the execution and development of other
programs
• Operating systems
Introduction to Programming
What is a program
• A set of instructions for the computer
– In a logical order
– For a specific purpose
– Using the defined resources
Introduction to Programming
Program Writing
Source Program
Compile
Library routines
Edit Link
Other object files
Think Load
Execute
Introduction to Programming
IDEs
• Integrated Development Environments or IDEs
– Supports the entire software development cycle
• MS Visual C++, Borland
• Provides all the capabilities for developing software
– Editor
– Compiler
– Linker
– Loader
– Debugger
– Viewer
Introduction to Programming
A Sample Program
// first program in C++
#include <iostream.h>
void main (void)
{
cout << "Hello …";
}
Introduction to Programming
Executing the Program
// first program in C++
#include <iostream.h>
void main (void)
{
cout << "Hello …";
}
Source file “Test.cpp”
Compile
Test.cpp Test.obj
Link
Test.obj + Libraries Test.exe
Introduction to Programming
A Sample Program
// first program in C++ A comment
#include <iostream.h> Header File : contains function declarations
void main (void) Start function
{
cout << "Hello …"; Program Statements
}
Introduction to Programming
Program Output
• Output Terminal?
– Console
– Data File
– Terminal ports/ sockets
• Console Output
– cout <<
– In the header file “iostream”
Introduction to Programming
Escape Sequences
Escape Sequence Description
\n Newline. Position the screen cursor to the beginning of the
next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning
of the current line; do not advance to the next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote character.
Console Output
• How to generate the following output:
******************
Name
My name
Roll No
My roll no
******************
Introduction to Programming
Good Programming Practices
• First design the basic flow chart of the program
• Write the pseudo code
– Simple English statements
• Algorithm
– English and Programming terms
• Code the algorithm
– Use already given libraries, don’t re-invent the wheel
• Check for errors
– Different types of errors
• Example : Even /odd numbers
Introduction to Programming
Program Errors
Compiler Errors
#include <iostream.h>
void main (void)
{
cout << "Hello …"
}
Error Test.cpp 4: Statement Missing ; in function main()
Error Test.cpp 4: Compound Statement missing } in function main()
Program Errors
Linker Errors
#include <iostream.h>
void Main (void)
{
cout << "Hello …";
}
Linker Error: Undefined Symbol _main
Program Errors
Run-Time Errors
#include <iostream.h>
void main (void)
{
int a=0;
int b=10;
double c = b/a;
}
These errors don’t reveal themselves until the program executes.
Program Errors
Conceptual Errors
#include <iostream.h>
void main (void)
{
int a=4;
int b=10;
int c = b/a;
cout << “c = “<< c;
}
The program is not doing what you expect it to do.
C++ Data Types
Integer Data types
char
short
int
long
Floating Point Data types
float
double
long double
Programming Basics
C++ Data Types
Data Type No. of Bytes No. of Bits
char 1 8
short 2 16
int 4 32
long 4 32
float 4 32
double 8 64
long double 10 80
Programming Basics
C++ Data Types
• Integer Data Types
– Range
– Unsigned Data Types
Type Sign Size Min Value Max Value
short signed 16 bits -32768 32767
unsigned 0 65535
int Signed 32 bits -2,147,483,648 2,147,483,647
unsigned 0 4,294,967,295
long signed 32 bits -2,147,483,648 2,147,483,647
unsigned 0 4,294,967,295
Programming Basics
Declarations
• Declarations
– Constant Declarations
– Variable Declarations
• Constant Declarations
Constants are used to store values that never change
during the program execution.
Using constants makes programs more readable and
maintainable.
Programming Basics
Declarations
• Constant Declarations
– Syntax
const <type> <identifier> = <expression>;
Example
const double PI = 3.1459;
Programming Basics
Declarations
• Variable Declarations
– Variables are used to store values that can be changed
during the program execution
Syntax:
< type > < identifier >;
< type > < identifier > = < expression >;
Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14
Programming Basics
Declarations
• A variable has a type and it can contain only values of that
type. For example, a variable of the type int can only hold
integer values
• Variables are not automatically initialized. For example, after
declaration
int sum;
the value of the variable sum can be anything (garbage).
• Thus, it is good practice to initialize variables when they are
declared. Once a value has been placed in a variable it stays
there until the program deliberately alters it.
Programming Basics
Declarations
• Constants and variables must be declared before
they can be used
• When you declare a constant or a variable, the
compiler:
Reserves a memory location in which to store the value of
the constant or variable.
Associates the name of the constant or variable with the
memory location.
int integer1 = 45; integer1 45
Programming Basics
Identifiers
• Series of Characters (letters, digits, underscores)
• Must NOT start with a digit (0 – 9)
• Must not be a C++ keyword
• Case Sensitive
Programming Basics
Example
1
2 // Addition program.
3 #include <iostream.h>
4
5 // function main begins program execution
6 void main()
7 {
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; // variable in which sum will be stored
11
12 cout << "Enter first integer:\n"; // prompt
13 cin >> integer1; // read an integer
14
15 cout << "Enter second integer:\n"; // prompt
16 cin >> integer2; // read an integer
17
18 sum = integer1 + integer2; // assign result to sum
19
20 cout << "Sum is " << sum << endl; // print sum
21
22
23
24 } // end function main
Programming Basics
Input Value
• Input Source?
– Console
– Data File
• Console Input
– cin >>
– In the header file “iostream”
Programming Basics
Arithmetic Operators
• Arithmetic calculations
–*
• Multiplication
–/
• Division
• Integer division truncates remainder
7 / 5 evaluates to 1
–%
• Modulus operator returns remainder
7 % 5 evaluates to 2
– + and –
• Addition and Subtraction
Programming Basics
Arithmetic Operators
• Rules of operator precedence
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated
first. If there are several pairs of parentheses
“on the same level” (i.e., not nested), they are
evaluated left to right.
*, /, or % Multiplication Evaluated second. If there are several, they re
Division evaluated left to right.
Modulus
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Programming Basics
Arithmetic Operators
• Priority of operators
– 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
– Parentheses are included when one is not sure
• sizeof ( )
– returns the size in bytes
– a = sizeof (char)
Programming Basics
Arithmetic Operators
• Arithmetic Assignment Operators
a = a + b;
a+=b;
void main(void)
{
int number = 15;
number +=10;
cout << number << endl; 25
number -=7;
18
cout << number << endl;
number *=2; 36
cout << number << endl;
number %=2; 0
cout << number << endl;
}
Programming Basics
Arithmetic Operators
• Increment Operators
count = count + 1;
count +=1;
count++; OR ++count;
int a = 5; int a = 5;
int b = 10; int b = 10;
int c = a * b++; int c = a * +
+b;
50 55
Programming Basics
Arithmetic Operators
• Decrement Operators
count = count - 1;
count -=1;
count--; OR --count;
postfix prefix
Programming Basics
Arithmetic Operators
void main()
{
int count = 10;
cout << count << endl;
cout << ++count << endl;
cout << count << endl; 10
cout << count++ << endl; 11
cout << count << endl; 11
} 11
12
Programming Basics
Type Conversion
• Automatic Type Conversion
• Casting
Automatic Type Conversion:
void main (void)
{
int number = 2;
float factor = 1.5;
double result = number * factor;
cout << “Result is: “ << result;
}
Programming Basics
Type Conversion
• Casting
void main(void)
{
short number = 30000; //-32768 to 32767
short result = (number * 10) / 10;
cout << “Result is: “ << result; //Result Incorrect
number = 30000;
result = ( long(number) * 10 ) / 10; //Casting
cout << “Result is: “ << result;
Programming Basics
Relational Operators
• To evaluate comparison between two expressions
– Result : True / False
Standard algebraic C++ equality Example Meaning of
equality operator or or relational of C++ C++ condition
relational operator operator condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
Programming Basics
Relational Operators
• Examples
(7 == 5) would return false
(3 != 2) would return true
(6 >= 6) would return true
• If a=2, b=3 and c=6
(a*b >= c) would return true since it is (2*3 >= 6)
(b+4 > a*c) would return false since it is (3+4 > 2*6)
((b=2) == a) would return true
Programming Basics
Equality (==) and Assg (=) Operators
• Common error : Does not cause syntax errors
• Example
if ( payCode == 4 )
cout << "You get a bonus!“;
• If == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!“;
– PayCode set to 4 (no matter what it was before)
– Statement is true (since 4 is non-zero)
– Bonus given in every case
Programming Basics
Logical Operators
• NOT, AND, OR : ( !, &&, || )
– Operator ! is equivalent to Boolean operation NOT
• ! (5 == 5) returns false
• ! (6 <= 4) returns true
• ! true returns false.
• ! false returns true.
– Logic operators && and || are used when evaluating two
expressions to obtain a single result
• ((5 == 5) && (3 > 6)) returns false (true && false)
• ((5 == 5) || (3 > 6)) returns true ( true || false ).
Programming Basics
Conditional Operators
• condition ? result1 : result2
if condition is true the expression will return result1, if not
it will return result2
• Examples
7==5 ? 4 : 3 returns 3 since 7 is not equal to 5.
7==5+2 ? 4 : 3 returns 4 since 7 is equal to 5+2
a>b ? a : b returns the greater one, a or b
Programming Basics
Bitwise Operators
• Bitwise Operators ( &, |, ^, ~, <<, >> )
& AND Logical AND
| OR Logical OR
^ XOR Logical exclusive OR
~ NOT Complement to one (bit inversion)
<< SHL Shift Left
>> SHR Shift Right
Programming Basics