0% found this document useful (0 votes)
20 views10 pages

Grade 11 ICTNote

Uploaded by

fikiralex644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views10 pages

Grade 11 ICTNote

Uploaded by

fikiralex644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Blessed G/Michael Catholic Secondary School

and Higher Education Preparatory School


2 Semester ICT handout for Grade 11th
nd

Introduction to C++ programming


Computer Languages
A computer cannot understand any commands that you may give in English or in any other language. It has its own
set of instructions for communication, or what we call computer languages .The user of a computer must be able to
communicate with it. That means, he must be able to give the computer commands and understand the output that
the computer generates. Basically, there are two main categories of computer languages:-
Low Level Language and High Level Language.
1. Low Level Languages
Low level languages are the basic computer instructions. These low level languages are very easily understandable
by the machine. The main function of low level languages is to interact with the hardware of the computer.
Machine Language
The language was first developed to interact with the first generation computers. It is written in binary code or
machine code only 0 and 1 bit.
Assembly Language
It uses English words, names, and symbols additional to 0 and 1.
2. High Level Language
When we talk about high level languages, these are programming languages. Some prominent examples are
PASCAL, FORTRAN, C++ etc.
ALGORITHMS
An algorithm is a representation of a solution to a problem. If a problem can be defined as a difference between a
desired situation and the current situation in which one is, then a problem solution is a procedure, or method, for
transforming the current situation to the desired one.
• Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process.
• A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each shape
represents a step in the process, and the arrows show the order in which they occur.
Flowcharting Symbols

General Rules for flowcharting


1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all
flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not
exceed 3 symbols. Connectors are used to connect breaks in the flowchart.
Examples are
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Example 1. Design an algorithm and the corresponding flowchart for adding the test scores as given below: 26, 49,
98, 87, 62, 75

1. Start
2. Sum = 0 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop

PSEUDOCODE
Pseudocode is one of the tools that can be used to write a preliminary plan that can be developed into a computer program.
Pseudocode is a generic way of describing an algorithm without use of any specific programming language syntax. It is, as
the name suggests, pseudo code it cannot be executed on a real computer, but it models and resembles real programming
code, and is written at roughly the same level of detail.
For example, for finding the average of six numbers, and the
sum of the numbers is given.
The pseudocode will be as follows
Start
Get the sum
Average = sum / 6
Output the average
Stop
C++ = C plus plus
C++ is a middle-level programming language developed by Bjarne Stroustrup at Bell Labs. C++ runs on a variety of platforms,
such as Windows, Mac OS, and the various versions of UNIX. C++ adds object-oriented features to its predecessor, C.

#include <iostream>

Using namespace std;

int main() {

cout << “Hello world!”;

return 0;

After you write a C++ program you compile it; that is, you run a program called compiler that checks whether the program
follows the C++ syntax

-indentation is for the convenience of the reader; compiler ignores all spaces and new line; the delimiter for the compile is
the semicolon.

-if it finds errors, it lists them

-If there are no errors, it translates the C++ program into a program in machine language which you can execute
The istream and ostream classes derived from ios form a user-friendly interface for stream manipulation. The istream class
is used for reading streams and the ostream class is used for writing to streams.

The operator >> is defined in istream and << is defined in ostream. The iostream class is derived by multiple inheritance from
istream and ostream and thus offers the functionality of both classes. Further stream classes , a file management class. This
allows the developer to use the techniques described for file manipulation. These classes, which also contain methods for
opening and closing files.

 Any C++ program file should be saved with file name extension “ .CPP ”
 The first character is the #. This character is a signal to the preprocessor. Each time you start your
compiler, the preprocessor runs through the program and looks for the pound (#) symbols and act on
those lines before the compiler runs.
 include instruction is a preprocessor instruction that directs the compiler to include a copy of the file
specified in the angle brackets in the source code.
 The effects of line 1, i.e. include<iostream> is to include the file iostream into the program as if the
programmer had actually typed it.
 When the program starts, main() is called automatically.
 Every C++ program has a main() function.
 If the return value type for main() is void, means main function will not return a value to the caller
(which is the operating system).
 The main function can be made to return a value to the operating system.
 The Left French brace “{“signals the beginning of the main function body and the corresponding Right
French Brace “}” signals the end of the main function body. Every Left French Brace needs to have a
corresponding Right French Brace.
 The lines we find between the braces are statements or said to be the body of the function.
 A statement is a computation step which may produce a value or interact with input and output streams.
 The end of a single statement ends with semicolon (;).
A brief look at cout and cin
 cout is an object used for printing data to the screen.
 To print a value to the screen, write the word cout, followed by the insertion operator also called output
redirection operator (<<) and the object to be printed on the screen.
 Syntax: Cout<<Object;
 The object at the right hand side can be:
• A literal string: “Hello World”
• A variable: a place holder in memory
 cin is an object used for taking input from the keyboard.
 To take input from the keyboard, write the word cin, followed by the input redirection operator (>>)
and the object name to hold the input value.
 Syntax: Cin>>Object
 cin will take value from the keyboard and store it in the memory. Thus the cin statement needs a
variable which is a reserved memory place holder.
 Both << and >> return their right operand as their result, enabling multiple input or multiple output
operations to be combined into one statement.
The following example will illustrate how multiple input and output can be performed:
E.g.: cin>>var1>>var2>>var3;
Here three different values will be entered for the three variables. The input should be
separated by a space, tan or newline for each variable.
cout<<var1<<”, “<<var2<<” and “<<var3;
Here the values of the three variables will be printed where there is a “,” (comma) between
the first and the second variables and the “and” word between the second and the third.
Putting Comments on C++ programs
A comment is a piece of descriptive text which explains some aspect of a program.
Program comments are text totally ignored by the compiler and are only intended to inform the reader
how the source code is working at any particular point in the program.
C++ provides two types of comment delimiters:
Single Line Comment: Anything after // {double forward slash} (until the end of the line on which it
appears) is considered a comment.
o Eg: cout<<var1; //this line prints the value of var1
Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment.
Eg:
/*this is a kind of comment where
Multiple lines can be enclosed in
one C++ program */
Comments should be used to enhance (not to hinder) the readability of a program. A comment should
be easier to read and understand than the code which it tries to explain. Over-use of comments can
lead to even less readability.
Use of descriptive names for variables and other entities in a program, and proper indentation of the
code can reduce the need for using comments.
Operators
 An operator is a symbol that makes the machine to take an action.
 Different Operators act on one or more operands and can also have different kinds of operators.
 C++ provides several categories of operators, including the following:
 Assignment operator
 Arithmetic operator
 Relational operator
 Logical operator
 Increment/decrement operator
 Conditional operator
 Comma operator
Assignment operator (=).
The assignment operator causes the operand on the left side of the assignment statement to have its value
changed to the value on the right side of the statement.
 Syntax: Operand1=Operand2;
 Operand1 is always a variable
 Operand2 can be one or combination of:
• A literal constant: Eg: x=12;
• A variable: Eg: x=y;
• An expression: Eg: x=y+2;
Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
 Compound assignment operator is the combination of the assignment operator with other operators
like arithmetic and bit wise operators.
 The assignment operator has a number of variants, obtained by combining it with other operators.
E.g.: Value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a – 5;
a /= b; is equivalent to a = a / b;
price *= units + 1 is equivalent to price = price * (units + 1);
Arithmetic operators (+, -, *, /, %).
 Except for remainder or modulo (%), all other arithmetic operators can accept a mix of integers and real
operands. Generally, if both operands are integers then, the result will be an integer. However, if one or
both operands are real then the result will be real.
 When both operands of the division operator (/) are integers, then the division is performed as an
integer division and not the normal division we are used to.
 Integer division always results in an integer outcome.
 Division of integer by integer will not round off to the next integer
E.g.: 9/2 gives 4 not 4.5
-9/2 gives -4 not -4.5
 To obtain a real division when both operands are integers, you should cast one of the operands to
be real. E.g.: int cost = 100;
int volume = 80;
double unitPrice = cost/(double)volume;
 The module (%) is an operator that gives the remainder of a division of two integer values. For
instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a remainder of
1; the result is therefore 1.
E.g.:
a = 11 % 3 => a is 2
Relational operator (==, ! =, > , <, >=, <=).
 In order to evaluate a comparison between two expressions, we can use the relational operator.
 The result of a relational operator is a Boolean value that can only be true or false according to the
result of the comparison.
E.g.:
(7 = = 5) would return false or returns 0
(5 > 4) would return true or returns 1
 The operands of a relational operator must evaluate to a number. Characters are valid operands
since they are represented by numeric values.
For E.g.: ‘A’ < ‘F’ would return true or 1. it is like (65 < 70)
Logical Operators (! , &&, ||):
 Logical negation (!) is a unary operator, which negates the logical value of its operand. If its operand is
non zero, it produces 0, and if it is 0 it produce 1.
 Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it produces 1.
 Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces 1.
E.g.: !20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas only zero represents the
logical false.
Increment/Decrement Operators: (++) and (--)
 The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
 E.g.: if a was 10 and if a++ is executed then a will automatically changed to 11.
Prefix and Postfix:
 The prefix type is written before the variable. Eg (++ myAge), whereas the postfix type appears after
the variable name (myAge ++).
 Prefix and postfix operators cannot be used at once on a single variable: Eg: ++age-- or --age++ or
++age++ or - - age - - is invalid
 In a simple statement, either type may be used. But in complex statements, there will be a difference.
 The prefix operator is evaluated before the assignment, and the postfix operator is evaluated after the
assignment.
E.g.
int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
(auto increment postfix) y= k++ + 10; //gives 15 for y
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y

Conditional Operator (?:)


 The conditional operator takes three operands. It has the general form: Syntax:
operand1 ? operand2 : operand3
 First operand1 is a relational expression and will be evaluated. If the result of the evaluation is non zero
(which means TRUE), then operand2 will be the final result. Otherwise, operand3 is the final result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X will be assigned to Z otherwise (if X>=Y) the value
of Y will be assigned to Z.
E.g
int m=1,n=2,min;
min = (m < n ? m : n);
The value stored in min is 1.
E.g.:
(7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
Comma Operator (,)
 Multiple expressions can be combined into one expression using the comma operator.
 The comma operator takes two operands. Operand1,Operand2
 The comma operator can be used during multiple declaration, for the condition operator and for
function declaration, etc
 It the first evaluates the left operand and then the right operand, and returns the value of the latter as
the final outcome. E.g.
int m,n,min;
int mCount = 0, nCount = 0;
min = (m < n ? (mCount++ , m) : (nCount++ , n));
Here, when m is less than n, mCount++ is evaluated and the value of m is stored in min.
otherwise, nCount++ is evaluated and the value of n is stored in min.
Operator Precedence
The order in which operators are evaluated in an expression is significant and is determined by precedence
rules. Operators in higher levels take precedence over operators in lower levels.
Precedence Table:
Level Operator Order
Highest ++ -- (post fix) Right to left
sizeof() ++ -- (prefix) Right to left
*/% Left to right
+- Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Left to right
= ,+=, -=, *=, /=,^= ,%=, &= ,|= ,<<= ,>>= Right to left
, Left to right
E.g a = = b + c * d
c * d is evaluated first because * has a higher precedence than + and = =.
The result is then added to b because + has a higher precedence than = =
And then == is evaluated.
Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the
column on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated followed by
a = b.
a. Constants
Data items are sometimes required to keep their values throughout the program, hence the
term constant. A constant is a specific value or character string used explicitly in an
operation.
b. Variables and Variable names
A variable is a symbolic name assigned to a data item by the programmer. At any particular time, a variable will
stand for one particular data, called the value of a variable, which may change from time to time during a computing
process. The value of a variable may change many times during the execution of a program. A variable is usually
given a name by the programmer.
The assignment operation has the form:
variable: = expression. (Pascal)
Variable = expression. (C/C++/Java)
The assignment operation is used to assign a name to a value. Thus it is used whenever you need to keep track
of a value that is needed later. Some typical uses include:
• initialize a variable ( count = 0 )
• increment/decrement a counter ( count = count + 1 )
• accumulate values ( sum = sum + item )
• capture the result of a computation ( y = 3*x + 4 )
• swap two values ( t = x; x = y; y = t )
The assignment operator is not commute i.e. x = e is not the same as e = x. The variable
must be declared. Variables used in the expression must be defined (have values). The
type of the expression must be compatible with the type of the variable.
The order in which assignments are performed is important for example, if the first and
second assignments in the swap sequence were interchanged, x and y would end up
assigned to the same value. The input operation and the output operation share some of
the same constraints.

Looping
Many programming problems are solved by repeatedly acting on the same data. There are two ways to do this: recursion
and iteration. Iteration means doing the same thing again and again. The principal method of iteration is the loop.

The do...while Statement


The syntax for the do...whilestatement is as follows:
do
statement
while (condition);
statement is executed, and then condition is evaluated. If condition is TRUE, the loop is repeated; otherwise, the
loop ends. The statements and conditions are otherwise identical to the whileloop.
The do...whileloop executes the body of the loop before its condition is tested and ensures that the body always
executes at least one time.
while ( ) Loops
It is possible that the body of a whileloop will never execute. The whilestatement checks its condition before executing any of
its statements, and if the condition evaluates false, the entire body of the whileloop is skipped.

The condition tested in a whileloop can be any valid C++ expression. As long as that condition remains true, the
whileloop will continue. You can create a loop that will never end by using the number 1 for the condition to be
tested. Since 1 is always true, the loop will never end, unless a breakstatement is reached.

#include<iostream>
using namespace std;
int main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
}
return 0;
}

for Loops
A for loop combines three steps into one statement. The three steps are initialization, test, and increment. A for statement
consists of the keyword for followed by a pair of parentheses. Within the parentheses are three statements separated by
semicolons. A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.

Syntax
for ( init; condition; increment ) {
statement(s);
}
The if-else Statement
• A branching statement that chooses between two possible actions.
• syntax
if (Boolean_Expression)
Statement_1
else
Statement_2
example
if (count < 3)
total = 0;
else
total = total + count;

1. Write a program that asks the user to type 2 integers A and B and exchange the value of A and B.

Solution #1

#include<iostream>
using namespace std;

int main()
{
double a,b,temp;

cout<<"Type the value of a : ";cin>>a;


cout<<"Type the value of b : ";cin>>b;

temp=a;
a=b;
b=temp;
cout<<"The value of a is "<<a<<endl;
cout<<"The value of b is "<<b<<endl;

return 0;
}
2. Write a program that asks the user to type the price without tax of one kilogram of tomatoes, the number of
kilograms you want to buy and the tax in percent units. The program must write the total price including taxes.

Solution #1
//by sniper.org
#include<iostream>
using namespace std;
int main()
{
double price_without_taxes,weight,taxes,total;

cout<<"Type the price of 1 kg of tomatoes without taxes : ";cin>>price_without_taxes;


cout<<"How much tomatoes do you want (in kilogram) : ";cin>>weight;
cout<<"What is the tax in percent : ";cin>>taxes;

total= ((((price_without_taxes*taxes)/100)+ price_without_taxes)*weight);

cout<<"The total price is : "<<total<<endl;

return 0;
}

3. Write a program that asks the user to two find the square of a given number.

Solution #1

#include <iostream>
using namespace std;
int main()
{
int j;
for(j=0; j<15; j++)
cout << j * j << " ";
cout << endl;
return 0;
}
4. Write a program that asks the user to two find the cube of a given number.
#include <iostream>
Using namespace std;
#include <iomanip.h>
int main(){
int numb;
for(numb=1; numb<=10; numb++)
{
cout << setw(4) << numb;
int cube = numb*numb*numb;
cout << setw(6) << cube << endl;
}
return 0;
}

C++ Program to Find Sum of First n Natural Numbers

You might also like