Professional Documents
Culture Documents
Basics of programming
What is a program?
Types of programs
There are all kinds of different programs used today, for all types of purposes.
All programs are written with some form of programming language and C++
can be used for in any type of application. Examples of different types of
programs, (also called software), include:
Operating Systems
Declare A, B, C
Read A, B
C = A+B
Write C
Stop
Basics of C++
The following simple C++ program demonstrates the basic structure of C++
programs.
//include headers; these are modules that include functions that you may use
in your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream.h
#include <iostream.h>
int main() {
//variable declaration
//read values input from user
//computation and print output to user
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:
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
Notes
What follows after // on the same line is considered comment indentation is
for the convenience of the reader; compiler ignores all spaces and new line; the
delimiter for the compiler is the semicolon
all statements ended by semicolon
Lower vs. upper case matters!!
Void is different than void
Main is different that main
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing.
Their purpose is only to allow the programmer to insert notes or descriptions
embedded within the source code. C++ supports two ways to insert comments:
// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the
pair of slash signs (//) is found up to the end of that same line. The second
one, known as block comment, discards everything between the /* characters
and the first appearance of the */ characters, with the possibility of including
more than one line. Adding comments to our program may make it look like:
/* my second program in C++
with more comments */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++ program
return 0;
}
Program Output: Hello World! I'm a C++ program
Program Errors
Syntax errors
Violation of the grammar rules of the language
Discovered by the compiler
Error messages may not always show correct location of Errors
Example:
#include <iostream>
using namespace std
int main()
{
cout << "Programming is fun << endl;
return 0;
}
Run-time errors
Error conditions detected by the computer at run-time
Example:
#include <iostream>
using namespace std;
int main()
{
int i = 4;
int j = 0;
cout << i / j << endl;
return 0;
}
Here, i and j are called variables. i has a value of 4 and j has a value of 0. i / j
in line 8 causes a runtime error of division by zero.
Logic errors
Errors in the program’s algorithm
Most difficult to diagnose
Computer does not recognize such an error
Example:
#include <iostream>
using namespace std;
int main()
{
cout << "Celsius 35 is Fahrenheit degree " << endl;
cout << (9 / 5) * 35 + 32 << endl;
return 0;
}
Celsius 35 is Fahrenheit degree
67
Escape Character
The backslash (\) is called an escape character. It indicates that a “special”
character is to be output. When a backslash is encountered in a string of
characters, the next character is combined with the backslash to form an
escape sequence. Some common escape sequences are
Escape Sequence Meaning
\n .......................................................New line
\t ........................................................Horizontal Tab
\v .......................................................Vertical tab
\b ......................................................Backspace
\' ................................................ Single quote (')
\" .............................................. Double quote (")
\? ..............................................Question mark (?)
\\ ...............................................Backslash (\)
#include <iostream>
usingnamespace std;
int main (){
cout << “Abebe”<<”\t”<<25<<endl;
cout << “Zerihun”<<”\t”<<30<<endl;
cout << “Frehiwot”<<”\t”<<27<<endl;
cout << “Chala ”<<”\t”<<31<<endl;
}
Variable declaration and initialization
Basic Data Types
C++ supports a large number of data types. The built in or basic data types
Supported by C++ are integer, floating point and character. C++ also provides
The data type bool for variables that can hold only the values true and false.
Some commonly used data types are summarized in table along with
description.
Type Description
Int Small integer number
long int Large integer number
float Small real number
double Double precision real number
long double Long double precision real number
char A Single Character
bool Stores either value true or false.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables
the compiler to make available the appropriate type of location in the memory.
float total;
You can declare more than one variable of same type in a single statement
int x, y;
Example:
// operating with variables
#include <iostream>
usingnamespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
Initialization of variable
Variable is a location in the computer memory which can store data and is
given a symbolic name for easy reference. The variables can be used to hold
different values at different times during the execution of a program.
Constants
A variable which does not change its value during execution of a program is
Known as a constant variable. Any attempt to change the value of a constant
Will result in an error message. A constant in C++ can be of any of the basic
Data types, const qualifier can be used to declare constant as shown below:
const float PI = 3.1415;
The above declaration means that PI is a constant of float types having
a value 3.1415.
Examples of valid constant declarations are:
const int RATE = 50;
const float PI = 3.1415;
const char CH = 'A';
Operators
Operators are special symbols used for specific purposes. C++ provides six
Types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators,
Assignment operators, Conditional operators, Comma operator
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic
(Numeric) operation. You can use the operators +, -, *, and / with both integral
And floating-point data types. Modulus or remainder % operator is used only
With the integral data type. Operators that have two operands are called binary
operators.
Relational operators
The relational operators are used to test the relation between two values. All
Relational operators are binary operators and therefore require two operands. A
Relational expression returns zero when the relation is false and a non-zero
When it is true. The following table shows the relational operators.
Relational Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to
Logical operators
The logical operators are used to combine one or more relational expression.
The logical operators are
Operators Meaning
|| OR
&& AND
! NOT
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This
Operator takes the expression on its right-hand-side and places it into the
Variable on its left-hand-side.
For example:
m = 5;
The operator takes the expression on the right, 5, and stores it in the variable
On the left, m.
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
In addition to standard assignment operator shown above, C++ also support
Compound assignment operators.
Compound Assignment Operators
Operator Example Equivalent to
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ =2 A=A/2
*= A*=2 A=A*2
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<< "\nEnter first number : ";
cin>>a;
cout<<"\nEnter second number : ";
cin>>b;
c=a+b;
cout<<"\nThe Sum is : "<<c;
return 0;
}
Review exercise
1. Write an algorithm, draw flowchart for the following questions (some of
these examples will be done in class) and display the result on screen
a. Check a number is negative or not.
b. Find the largest among three different numbers entered by user
d. Factorial of a number entered by the user.
e. Find the Fibonacci series till term <=1000.
f. Sums all the even numbers between 1 and 20 inclusive.
2. What do you understand by expression ‘ # include <iostream>’ in a program
?
3. What is wrong with following statements? Also give the correct version.
(a) int x = 6.75;
(b) int shot = 8;
(c) char m = A;
6. Explain the difference between pre and post increments, i.e. ++ n and n++.
7. Evaluate the following for int n = 8 ;
(a) ++n += 3;
(b) –n % 3 += 2;
8. Evaluate the following for int n = 4;.
(a) ++n*n++;
(b) ++n*n– – ;
(c) 2*++n + 3 * – –n;
(d) ++n += 3;
9. Evaluate the following expressions for int n = 20 ;
(a) n /= 5;
(b) n += 8;
(c) n %= 7;
#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
int m = 6,n = 2, a=0,b=0,c=0,d=0,e=0;
a +=4 + ++m*n ;
b *=3+ -m*m ;
c +=2 +m *++m ;
d *=2* + m*m-- ;
e -=2*++m / m-- ;
cout<<“a = “<<a<<“, “<<“b = “ << b<<“, c = “<<c<<“, d
= “<<d <<“, e = “<<e <<endl;
return 0 ;
}
#include <iostream>
using namespace std;
int main (){
m += 2;
n *= 4;
p –= 3;
s /= 2;
cout <<“m = ”<<m <<“, n = ”<<n<<“, p = ”<<p<<“, s = ”
<<s<<endl;
q %= 4 + (n /= 4);
cout << “ q = “ << q << endl;
return 0;
}