1
Programming - 1
Computer Science Department
Jazan University
2
1.1Machine Language
The only languages understood by a computer is its own machine language. Machine Languages are machine dependent.
Machine Language programming was very slow and was difficult to understand for most of the programmers.
1.2 Assembly Language
An assembly language is a low level programming language for computers and other programmable devices.
It implements a symbolic representation of the machine codes.
3
1.3 High level Language High level programming language is a more or
less independent of a particular type of computer.
Programs written in a high-level language must be translated into machine language by a compiler or interpreter.
Examples: C, PASCAL, C++, FORTRAN etc…
4
1.4 History of C and C++
C++ was written by Bjarne Stroustrup at Bell Labs during 1983-1985. C++ is an extension of C programming language.
5
1.5 Introduction to Programming
Comments: //, /* …. */
Preprocessor directives : #include
Function main
Body of the function Return statement Other statements
6
1.5.1 Comments
Explain programs to other programmers. Improve program readability
Ignored by compiler Single-line comment
Begin with // Example:
//allows program to output data to the screen. Multi-line comment
Start with /* End with */
7
1.5.2 Preprocessor Directives
Preprocessor directives Processed by preprocessor before compiling Begin with # Example:
#include <iostream> Tells preprocessor to include the input/output
stream header file <iostream>
White spaces Blank lines, space characters and tabs Delimiter, used to make programs easier to read Extra spaces are ignored by the compiler 8
1.5.3 Function Main
A part of every C++ program Exactly one function in a program must be
main
main is a Keyword. Keyword : A word in code that is reserved by
C++ for a specific use.
Header of function main : int main( ) Body is delimited by braces { }
9
1.5.4 Statements
Instruct the program to perform an action.
All statements end with a semicolon (;)
Examples :
return 0; std::cout << “Welcome to C++!\n ”;
10
1.5.5 return Statement
One of several means to exit a function
When used at the end of main
The value 0 indicates the program terminated successfully.
Example return 0;
11
1.5.6 Output statement std::cout << “Welcome to C++!\n”;
std::cout Standard output stream object. Defined in input/output stream header file <iostream> We are using a name (cout) that belongs to
“namespace” std. Normally outputs to computer screen.
Stream insertion operator << Value to right (right operand) inserted into left operand. The string of characters contained between “ ” after
the operator << shows on computer screen.12
1.5.6 Output statement (2)
Escape character: backslash : "\" Escape sequence: A character preceded by backslash
(\) Indicates “special” character output
Examples : "\n"
Newline. Cursor moves to beginning of next line on the screen
“\t” Horizontal tab. Move the screen cursor to the next tab stop.13
2.1 First program in C++
#include<iostream.h>#include<conio.h>void main( ){
cout<< “WELCOME IN C++ PROGRAM! “;
getch ();}
14
2.2 Modifying First C++ Program
Print text on one line using multiple statements.
Each stream insertion resumes printing where the previous one stopped.
Example statements:
cout << “Welcome ”;cout << “to C++!\n”;
15
2.2 Modifying First C++ Program
Print text on several lines using a single statement.
Each newline escape sequence positions the cursor to the beginning of the next line.
Two newline characters back to back outputs a blank line.
Example statement :
cout << “Welcome\nto\n\nC++!\n”; 16
2.3 Adding Integers
17
#include<iostream.h>#include<conio.h>void main( ){
int a, b, sum;cout<<“Enter value of a :”;cin>>a;cout>>”Enter value of b :”;cin>>b;sum = a + b;cout<< “Value of a and b : “ sum;getch ();
}
3.1 Memory Concepts Variable names
Every variable has name, type, size and value When new value placed into variable,
overwrites old value Writing to memory is destructive
Reading variables from memory nondestructive
Example: sum = number1 + number2;
Value of sum is overwritten Values of number1 and number2 remain intact 18
3.1 Continued….
19
Memory location showing the name and value
of variable number1.
3.1 Continued…
20
Memory locations after storing values for
number1 and number2.
3.1 Continued…
21
Memory locations after calculating and
storing the sum of number1 and number2.
3.2 Arithmetic Arithmetic operator are the binary operator
that takes two input to perform calculation.
Examples: Addition (+) Subtraction (-) Multiplication (*) Division (/) Modulus(%)
22
3.2 Rules of operator precedence
Operators in parentheses evaluated first
Multiplication, division, modulus applied next
Addition, subtraction applied last
23
3.3 Decision making : Equality and Relational Operators
24
Relational Operator
C++ operator
Sample C++ condition
Meaning of C++ condition
Relational Operator ( 4 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 Operator ( 2 operators)= == X == y X is equal to y
= != X != y X is not equal to y
Example: comparing integer using if statement, relational operator and equality operator
#include<iostream.h>void main(){
int x,y;cout<<”enter two integer”;cin>>x>>y;if(x==y)cout<<x<<”==”<<y;
if(x!=y)cout<<x<<”!=”<<y; 25
Example continued…
if(x<y)cout<<x<<”<”<<y;
if(x>y)cout<<x<<”>”<<y;
if(x<=y)cout<<x<<”<=”<<y;
if(x>=y)cout<<x<<”>=”<<y;
} 26
4.1 Control Statement: Introduction
Specifying the order in which statements (actions) execute in a computer program is called program control.
C++ provides the many building blocks that allow us to specify the logic required for member functions to perform their tasks some of them are :
If If…else while
27
4.2 Algorithms
A procedure for solving a problem in terms of
1. The action to execute2. The order in which the actions execute
is called an algorithm.
28
4.3 Pseudo code
Pseudo code is an artificial and informal language that helps us to develop algorithms without having to worry about the strict details of C++ language syntax.
29
4.3 Pseudo code example:
Example, Pseudo code that may be written to help a programmer to create the addition program.
1 Prompt the user to enter the first integer2 Input the first integer3 Prompt the user to enter the second integer4 Input the second integer
5 Add first integer and second integer, store result6 Display result
30
5.1 Control Structure
Three type of Control Structure:
31
5.1.1 Sequence Structure
Execution of C++ statements one after the other in the order in which they are written is called Sequence structure.
32
5.1.2 Selection Structure
Execution of C++ statements on the basic of specified condition is called selection structure.
C++ provides three types of selection structure:
33
5.1.2.1 Selection Structure contd..
a) If: if selection statement either performs
(selects) an action if a condition (predicate) is true or skips the action if the condition is false.
Example: If(grade>=60)cout << “passed”;
34
b) If-Else if-else selection statement performs an
action if a condition is true or performs a different action if the condition is false.
Example: If(grade>=60)
cout << “passed”; else
cout << ”fail”; 35
5.1.2.2 Selection Structure Cont.
c) Switch :
switch selection statement performs one of many different actions, depending on the value of an integer expression.
36
5.1.2.3 Selection Structure Cont.
5.1.3 Repetition Structure Looping statements that enable programs
to perform statements repeatedly as long as a condition remains true.
C++ provides three types of repetition statements : a) While b) For c) Do-While
37
Conditional Operator ? The conditional operator is ternary operator it takes
three operands. The operands, together with the conditional operator, form a conditional expression.
The first operand is a condition, The second operand is the value for the entire
conditional expression if the condition is True The third operand is the value if the condition is
false.
Example: cout << ( grade >= 60 ? "Passed" : "Failed" );
38
Nested if...else Statements:
Nested if … else statement test for multiple cases by placing if...else selection statements inside other if...else selection statements.
39
Nested if...else example: Example:
if ( studentGrade >= 90 ) cout << "A";
elseif ( studentGrade >= 80 )
cout << "B"; else if ( studentGrade >= 70 )
cout << "C"; else
if ( studentGrade >= 60 ) cout << "D";
else cout << "F"; 40
Keyword
A keyword is a word in a code that is reserve by C++ for a specific use.
Example: int, char, if, else, switch, while etc.
41
Block
A set of statement contain within a pair of braces ( { and } )is called a compound statement or Block
42
6.1 While Repetition Statement:
A repetition statement (also called a looping statement or a loop) allows the programmer to specify that a program should repeat an action while some condition remains true.
43
6.1 Example:
#include<iostream.h>Void main(){
int product = 3; while ( product <= 100)product = 3 * product;
}44
6.2 Formulating Algorithms: Counter-Controlled Repetition:
Counter-controlled repetition is often called definite repetition because the number of repetitions is known before the loop begins executing.
45
6.2 Program#include <iostream>void main(){ int total, gradeCounter, grade; total = 0; gradeCounter = 1; while ( gradeCounter <= 10 ) { cout << "Enter grade: "; cin >> grade;
46
6.2 Program continued…
total = total + grade; gradeCounter = gradeCounter + 1; } cout << "\nTotal of all 10 grades is " << total <<
endl;}
47
6.3 Formulating Algorithms: Sentinel-Controlled Repetition:
Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing.
48
6.3 Program:
#include <iostream>void main(){ int total, gradeCounter, grade; total = 0; gradeCounter = 0; cout << "Enter grade or -1 to quit: "; cin >> grade;
49
6.3 Program continued..
while ( grade != -1 ) { total = total + grade; gradeCounter = gradeCounter + 1; cout << "Enter grade or -1 to quit: "; cin >> grade; }}
50
7.1 Nested Control Statement
The only other structured way control statements can be connected, namely, by nesting one control statement within another.
51
7.1 Example:#include <iostream>#include<conio.h>void main(){
int passes = 0; int failures = 0; int studentCounter = 1; int result; // one exam result (1 = pass, 2 =
fail)
52
7.1 Example continued:
while ( studentCounter <= 10 ) { cout << "Enter result (1 = pass, 2 = fail): "; cin >> result; if ( result == 1 ) //if…else nested in while passes = passes + 1; else failures = failures + 1; studentCounter = studentCounter + 1; } } 53
7.2 Assignment Operators C++ provides several assignment
operators for abbreviating assignment expressions.
Example: c=c+3; c+=3;
Any statement of the form Variable = variable operator expression; Variable operator= expression;
54
7.2 Assignment Operators
Assignment operator
Sample expression
Explanation
+= C += 7 C = c + 7
-= D -= 4 D = d -4
*= e *=5 E = e * 5
/= F /= 3 F = f / 3
%= G %= 9 G = g % 9
55
7.3 Increment and decrement operators:
C++ also provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable.
Example:
++ Unary increment operator
-- Unary decrement operator56
Operator Called Sample expression
Explanation
++ Preincrement ++a Increment a by 1, then use new value of a in the expression in which a resides.
++ Postincrement
a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- Predecrement
--b Decrement b by 1, then use new value of b in the expression in which b resides.
-- Postdecrement
b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
57
7.3 Increment and decrement operators:
8.1 Essentials of Counter-Controlled Repetition
Counter-controlled repetition requires:
1.The name of a control variable (or loop counter)
2.The initial value of the control variable3.The loop-continuation condition that tests for
the final value of the control variable.4.The increment (or decrement) by which the
control variable is modified each time through the loop. 58
8.1 Example:#include <iostream>void main() {
int counter=1;while ( counter<=10)
{ cout << counter << " "; counter ++; } }
Output of the above Example: 1 2 3 4 5 6 7 8 9 10Output of the above Example: 1 2 3 4 5 6 7 8 9 10 59
8.2 for Repetition Statement:
for repetition statement specifies the counter-controlled repetition details in a single line of code:
for statement header components
60
8.2 Example:
#include <iostream.h>void main( ) { For (int counter=1; counter<=10; counter++)
cout<<counter<<" "; }
Output of the above Example: 1 2 3 4 5 6 7 8 9 10
61
9.1 Examples using the for statement:
Vary the control variable from 1 to 10 in increments of 1. for ( int i = 1; i <= 10; i++ )
Vary the control variable from 10 down to 1 in increments of -1 (that is, decrements of 1). for ( int i = 10; i >= 1; i-- )
Vary the control variable from 7 to 77 in steps of 7. for ( int i = 7; i <= 77; i += 7 )
Vary the control variable from 20 down to 2 in steps of -2. for ( int i = 20; i >= 2; i -= 2 )
62
9.2 do...while Repetition Statement:
The do...while repetition statement is similar to the while statement.
The do...while statement tests the loop-continuation condition after the loop body executes; therefore, the loop body always executes at least once.
63
9.2 Example:
#include <iostream.h>int main() {
int counter=1;do
{cout<<counter<<” “;counter++;
}while (counter<=10);
}64
9.3 Switch Multiple-Selection Statement:
C++ provides the switch multiple-selection statement to perform many different actions based on the possible values of a variable or expression.
Example:switch(day){ case 1:
cout<<”Saturday”;break;
} 65
9.3 Program:#include <iostream.h>void main(){
int day;cout<<”enter the day”;cin>>day;switch(day){
case 1:cout<<”Saturday”;break;
66
9.3 Program continued…case 2:
cout<<”Sunday”;break;
case 3:cout<<”Monday”;break;
case 4:cout<<”Tuesday”;break;
default: cout<<” incorrect entry”;break;} }
67
10.1 Break statement: The break statement, when executed
in a while, for , do…while, or switch control statement, causes immediate exit from that control statement.
Program execution continues with the next statement.
Example,
68
10.1 Example:
for (count=1; count<=10; count++){
if(count == 5)break; //break loop if x is 5cout<<count<<” “;
}cout<<”\n Broke out of the loop of count = “<<count;
69
10.2 Continue statement:
The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop.
70
10.2 Example:
for (count=1; count<=10; count++){
if(count == 5)continue; //Skips remaining code
on loopcout<<count<<” “;
}
71
10.3 Logical operators
C++ provides logical operators that are used to form more complex condition by combining simple conditions.
The logical operators are: && Logical AND || Logical OR ! Logical NOT
72
10.3.1 Logical AND(&&) operator
Logical AND(&&) operator is used when we wish to ensure that two conditions are both true before we choose a certain path of execution.
Example:
if(gender==’F’ && age>=65)seniorFemales++;
73
10.3.1 Logical AND(&&) operator
Expression 1
Expression 2
Expression 1 && Expression 2
False False False
False True False
True False False
True True True
74
10.3.2 Logical OR (||) operator
Logical OR (||) operator is used when we wish to ensure at some point in a program that either or both of two conditions are true before we choose a certain path of execution.
Example:if((semesterAverage>=90) || (finalExam>=90))
cout<<”Student grade is A”;75
10.3.2 Logical OR (||) operator
Expression 1
Expression 2
Expression 1 && Expression 2
False False False
False True True
True False True
True True True
76
10.3.3 logical negation (!) operator:
C++ provides the ! (logical NOT) operator to enable a programmer the “reverse” the meaning of a condition.
Unlike the && and || binary operators, which combine two conditions, the unary logical negation operator has only a single condition as an operand.
77
Expression ! Expression
False True
True Fasle
10.3.3 Example:
if( !(grade<= 59))
count<<”You have passed the examination”;
78
10.4 Confusing the Equality (==) and Assignment (=) operators
Example:
if( payCode == 4)cout<<”You get a bonus”;
but accidentally wroteif(payCode = 4)count<<”You get a bonus”;
79
11.1 Derived Data Types Data types that are derived from
fundamental data types are called derived data types. Derived data types don't create a new data type; instead, they add some functionality to the basic data types. Two derived data type are - Array & Pointer.
80
11.2 Array
An array is a group of memory locations related by the fact that they all have the same name and type.
81
11.2 Program:#include<iostream.h>Using namespace std;int A [ ] = {16, 2, 77, 40, 120};int n, result=0;int main ()
{ for ( n=0 ; n<5 ; n++ ) { result += A[n]; } cout << result; return 0;
} 82
12.1 Function
83
A function is a collection of statements that performs a specific task - a single, well-defined task.
This makes programs easier to read and maintain. Statements in function bodies are written only
once Reused from perhaps several locations in a
program Hidden from other functions Avoid repeating code
12.2 Function Prototype Also called a function declaration Indicates to the compiler:
Type of data returned by the function Function Signature
Name of the function Parameters the function expects to receive
Number of parameters Types of those parameters Order of those parameters
Example: int addTwoNumbers(int, int); Function prototype is provided before the function is
invoked. 84
12.3 Function definition:
85
Definition of a method: Header : Return type, Function Name,
Parameter(s) [type and name pair ]. Body : a collection of statements.
Example:
int addTwoNumbers (int numberOne, int numberTwo )
{ int sum; sum = numberOne + numberTwo;
return sum; }
12.4 Return Type:
The return type is the data type of the result returned to the caller function.
86
12.5 Function Call:
There are two main ways for calling a function:
1. Call by value2. Call by reference
87
12.6 Program:
#include<iostream.h>int square(int y){
int p;p=y*y;return p;
}88
12.6 Program continued:
void main(){
int i;i=10;cout<<square(i)<<"";
}
89