ch1 computer programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

Chapter One

Introduction to programming
Computer stand for :
 Common Operating Machine Particularly Used for Trade, Education, and Research
 Common Operating Machine Particularly Used for Technical, Education and Research
Computer is not an acronym, it is a word derived from a word "compute" which means to
calculate. So, in simple words you can say that computer is an electronic device which is used
for fast calculation.

 "A computer is a general purpose electronic device that is used to perform arithmetic
and logical operations automatically. A computer consists of a central processing unit
and some form of memory."
 A Computer is an electronic device that accepts data, performs
computations, and makes logical decisions according to instructions
that have been given to it; then produces meaningful information in a
form that is useful to the user.
 In current world we live in, computers are almost used in all walks of
life for different purposes. They have been deployed to solve different
real life problems, from the simplest game playing (calculator) up to
the complex nuclear energy production.

Computer programs:
 In order to solve a given problem, computers must be given the correct
instruction about how they can solve it.
 Its sets of instructions that control a computer’s processing of data.
 The terms computer programs, software programs, source code
or just programs are the instructions that tells the computer what to
do. Computer requires programs to function, and a computer programs
does nothing unless its instructions are executed by a CPU.
 Computer programs are often written by professionals known as
Computer Programmers (simply programmer).
 Source code is written in one of programming languages

Computer programming:

1|Page
By:-Abdela A.
Computer programming (often shortened to programming or coding)
is the process of writing, testing, debugging/troubleshooting, and
maintaining the source code of computer programs.

Writing computer programs means writing instructions that will make the
computer follow and run a program based on those instructions. Each
instruction is relatively simple, yet because of the computer's speed, it is
able to run millions of instructions in a second.

What is Programming Language?

A programming language is an artificial language that can be used to


control the behavior of a machine, particularly a computer. Programming
languages, like human languages (such as Afan Oromo, Amharic, English
etc), are defined through the use of syntactic and semantic rules, to
determine structure and meaning respectively.

 The syntax of a language describes the possible combinations of


symbols that form a syntactically correct program.
 The meaning given to a combination of symbols is handled by
semantics.
 Programming languages differ from natural languages in that natural
languages are only used for interaction between people, while
programming languages also allow humans to communicate
instructions to machines.
 A main purpose of programming languages is to provide instructions to
a computer. As such, programming languages differ from most other
forms of human expression in that they require a greater degree of
precision and completeness.
What skills do we need to be a programmer?
 For someone to be a programmer, in addition to basic skills in
computer, needs to have the following major skills:
Programming Language Skill: knowing one or more programming
language to talk to the computer and instruct the machine to perform a
task.

2|Page
By:-Abdela A.
Problem Solving Skill: skills on how to solve real world problem and
represent the solution in understandable format.
Algorithm Development: skill of coming up with sequence of simple and
human understandable set of instructions showing the step of solving the
problem. Those set of steps should not be dependent on any
programming language or machine

C++ Programming Basics:

History of C and C++:

If there is one language that defines the essence of programming today, it


is C++. It is the preeminent language for the development of high-
performance software. C++ is also the language from which both Java and
C# are derived. Simply stated, to be a professional programmer implies
competency in C++. It is the gateway to all of modern programming
language.
The history of C++ begins with C. The reason for this is easy to
understand: C++ is built upon the foundation of C. Thus, C++ is a
superset of C. C++ expanded and enhanced the C language to support
object-oriented programming. C++ also added several other
improvements to the C language, including an extended set of library
routines. However, much of the spirit and flavour of C++ is directly
inherited from C. Therefore, to fully understand and appreciate C++, you
need to understand the “how and why” behind C.
The C++ Programming Language is basically an extension of the C
Programming Language. The C Programming language was developed
from 1969-1973 at Bell labs; at the same time the UNIX operating system
was being developed there. C++ was written by Bjarne Stroustrup at Bell
Labs during 1983-1985. Prior to 1983, Bjarne Stroustrup added features to
3|Page
By:-Abdela A.
C and formed what he called "C with Classes" but later it was renamed C+
+ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal
C++ program.He had combined the use of classes and object-oriented

features with the power and efficiency of C. Difference between C and C+

+(c vs c+):
C++ is the extension of C language, in C++ you not only use new feature but also use C
features. The main difference between C and C++ is, C is the function or procedure oriented
programming language and C++ is the object oriented programming language

Characteristics of c++/ Important Features of C++:


 C++ is a statically typed and compiled programming
 Its general-purpose programming
 C++ is case sensitive :because it interprets uppercase and
lowercase letters differently
For example: Cow and cow are two different combinations of letters
 Simple Every C++ program can be written in simple English language
so that it is very easy to understand and developed by programmer.
 Platform dependent: A language is said to be platform dependent
whenever the program is execute in the same operating system where
that was developed and compiled but not run and execute on other
operating system. C++ is platform dependent language.

 Compiler based: C++ is a compiler based programming language


that means without compilation no C++ program can be executed.
First we need compiler to compile our program and then execute.
 Syntax based language’s++ is a strongly tight syntax based
programming language
4|Page
By:-Abdela A.
 C++ fully supports object-oriented programming but is not
purely Object Oriented, including the four pillars of object-oriented
development:
 Encapsulation
 Data hiding
 Inheritance
 Polymorphism
Note1: A programming language is said to use static typing when type
checking is performed during compile-time as opposed to run-time.
Note2: java is pure object oriented programming
Syntax and Structure of C++ program:
 To understand the basic parts of a simple program in C++, let’s have a
look at the following code:
1. // the first C++ program ……………………..comment
2. # include <iostream.h>………………………compiler directive
3. int main ( )-------------------------------------------man function
4. { -- ------------------------------opening
Output :Hello Welcome
brace
5. cout << "Hello Welcome !\n";----output stream
6. return 0;------------------------------------return statement
7. } -------------------------------------------closing braces

1. /*my first program in C++

Don’t use .h here */

2. #include <iostream>
3. using namespace std;
4. void main () Output :Hello World
5. {
6. cout << "Hello world!"<<endl;
7. }

5|Page
By:-Abdela A.
Many programmers make the last character printed by a function a newline (\n) and endl.
This ensures that the function will leave the screen cursor positioned at the beginning of a
new line.

A C++ program has the following structure:

 Comments
 Compiler directive
 main function
 Braces
 parenthesis

1. Comments (optional part of the program)

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are
considered comments and do not have any effect on the behaviour of the
program. The programmer can use them to include short explanations or
observations within the source code itself. In this case, the line is a brief
description of what our program is. Comments Are remarks that are ignored by
the complier and you may write a comment anywhere in the program

C++ provides two types of comment delimiters:

1. Single Line Comment:


 Anything after // {double forward slash} (until the end of the line on which it appears) is
considered a comment.
 Its c++ new version of the comments.
 We use this if our comments is only ends in one line/single line
Example: cout<<var1; //this line prints the value of var1

// my first program in C++

2. Multiple Line Comment (block):


 Anything enclosed by the pair /* and */ is considered a multiline comment.
6|Page
By:-Abdela A.
 Its known as block comment
 We use if our comment is more than one line
 Its C style types of comments

Example:

/*this is a kind of comment where


Multiple lines can be enclosed in one C++ program
*/
Note: - Every program should begin with a comment that describes the purpose of the
program, author, date and time
Use comments to:

• Explain the purpose of a program

• Keep notes regarding change to the source code

• Store the names of programmers for future reference

• Explain the parts of your program

1. Compiler directive:

Compiler directive is classified in to two:

1. Pre-processor

2. Header file

Pre-processor (#include)
Lines beginning with a hash sign (#) are directives for the pre-processor.
They are not regular code lines with expressions but indications for the
compiler's pre-processor.
In this case the directive #include<iostream> tells the pre-processor to
include the iostream standard file.
Header files (<iostream.h>)
 iostream.h is a standard C++ header file and contains definitions for
input and output
 Are instructions to the compiler rather than C++ instructions that
instruct the C++ compiler to load a file from disk into the current
program?
 C++ support many types of header which available in built-in library
7|Page
By:-Abdela A.
 However, in C++ we write more than one header file for one program
 We write header before main function and not written everywhere in
the program unlike comment
 A header file may be included in one of two ways.
 # include < iostream.h> or
 # include “iostream.h”
The header file in angle brackets means that file reside in standard include directory.
The header files in double quotes means that file reside in current directory.
Types of Header files System header files: It is comes with
compiler.

User header files: It is written by programmer.

1. List and discuss available c++ header file with their function?
2. Discuss types of error in programming with example?
3. What is the difference between object code and source code?
4. What is the similarities and difference between c and c++?
main () function
 Is a function that runs first in C++ programs
 This line corresponds to the beginning of the definition of the main
function.
 The main function is the point by where all C++ programs start their
execution, independently of its location within the source code.
 It does not matter whether there are other functions with other names
defined before or after it – the instructions contained within this
function's definition will always be the first ones to be executed in any
C++ program.
 For that same reason, it is essential that all C++ programs have a main
function.
 The word main is followed in the code by a pair of parentheses ( ).
That is because it is a function declaration:
 There are two types of main function in C++
 int main()
int main has return value i.e. return 0;
 void main()
8|Page
By:-Abdela A.
Void main has no return value
 Right after these parentheses we can find the body of the main
function enclosed in braces {}.
 What is contained within these braces is what the function does when
it is executed.
 Program execution starts by executing whatever instructions found in
the body of statement.
 Every C++ program must have only one main function.
 The parentheses () following the main to tell the compiler that main is
a function
A brief look at cout and cin
 cin---------------extraction operator (>>)
 cout---------------insertion operator (<<)
 cout is an object used for printing data to the screen.
 cout represents the standard output stream in C++, and the meaning
of the entire statement is to insert a sequence of characters (in this
case the Hello World sequence of characters) into the standard output
stream (which usually is the screen).
 To print a value to the screen, write the word cout, followed by the
insertion operator also called output or 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

9|Page
By:-Abdela A.
 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;
Braces {}
o Are used to mark the beginning and the end of a block of code.
o Every opening brace must have a corresponding closing brace .
Statements
 Are instructions and commands that make the computer work.
Each statement must end in semicolon (;).
 The semicolon tells the compiler that the statement is completed.
 Notice that the statement ends with a semicolon character (;). This
character is used to mark the end of the statement and in fact it
must be included at the end of all expression statements in all C+
+ programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement).
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;
The return statement causes the main function to finish. return may be
followed by a return code (in our example is followed by the return code
0). A return code of 0 for the main function is generally interpreted as the

10 | P a g e
By:-Abdela A.
program worked as expected without any errors during its execution. This
is the most usual way to end a C++ console program.
Basic Elements of c++(Tokens):
 C++ Tokens are the smallest individual units of a program .
 It’s the group of characters that forms a basic building block is called as Token. There are
the following five types of token in C++:

Comments
Keywords (reserved words)
Identifier
Constant/literals
Operators

Keywords (reserved words):

Reserved/Key words have a unique meaning within a C++ program. These symbols, the
reserved words, must not be used for any other purposes. In generally reserved words are:

 Words with special meaning to the compiler


 Must not be used for any other purposes
 Have a predefined meaning that can’t be changed
 All reserved words are in exist or written lower-case letters
 Used only for specific purpose
 May not be used as identifier
 C++ Language supports more than 64 keywords
 Keyword cannot used for the following
1. Declaring Variable Name
2. Declaring Class Name
3. Declaring Function Name
4. Declaring Object Name
5. Etc.

11 | P a g e
By:-Abdela A.
The following are some of the reserved words of C++/c:

Identifiers:

 Identifiers are the basic building blocks of a program. Various data items with symbolic
names in C++ are called as Identifiers.
12 | P a g e
By:-Abdela A.
Following data items are called as Identifier in C++ –

1. Names of functions
2. Names of arrays
3. Names of variable
4. Names of classes.

Rule for valid identifier:

 Consist only of letters(A-Z or a-z), the digits 0-9, or the underscore symbol( _)

 The length of an identifier is not limited

 Not be a reserved word/keyword.

 Start with only letter or underscore not begin with digit

 C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different

 The name of identifier cannot begin with a digit. However, Underscore can be used as first
character while declaring the identifier.

 Only alphabetic characters, digits and underscore (_) are permitted in C++ language for
declaring identifier.

 Other special characters(?,/,”,@,! etc) are not allowed for naming a variable / identifier

 Keywords cannot be used as Identifier

 Neither space nor marked letters can be part of an identifier.

 Similarly, the use of two consecutive underscore symbols, _ _, is forbidden.

The following is valid identifier:


 First //valid Length // valid
 Conversion //valid
days_in_year//valid
 payRate first_1//valid
 salary // valid identifier void// invalid
 salary2 // valid identifier _pressure // valid
 2salary // invalid identifier (begins with a digit)
 _salary22// invalid identifier

13 | P a g e
By:-Abdela A.
Characters Literals
Character literals are enclosed in single quotes. A character literal can be
a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0'). There are certain characters in C++ when they
are preceded by a backslash they will have special meaning and they are
used to represent like newline (\n) or tab (\t). Here, you have a list of
some of such escape sequence codes

Variables in C++ Programming

 Definition of variable
 Declaration of variable
 Initialization of variable
 Scope of variable

14 | P a g e
By:-Abdela A.
Definition of C++ variables
 Variables represent storage locations in the computer’s memory.
Constants are data items whose values cannot change while the
program is running. Variables allow you to store and work with data in
the computer’s memory.
 A variable provides us with named storage that our programs can
manipulate. Each variable in C++ has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.
 The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an
underscore. Upper and lowercase letters are distinct because C++ is
case-sensitive
 Variable consists of three things:

 data type
 variable name
 value

Variable Declaration in c++:

 Is the process of allocating sufficient memory space for the data in


term of variable?
 It’s assigning or creating data types for variable.

Syntax: Data type variable name;

Example: char name;


int age;
float GPA;
Data types in c++

While writing program in any language, you need to use various variables
to store various information. Variables are nothing but reserved memory
15 | P a g e
By:-Abdela A.
locations to store values. This means that when you create a variable you
reserve some space in memory.

Data type is a keyword used to identify type of data. It is used for storing
the input of the program into the main memory (RAM) of the computer by
allocating sufficient amount of memory space in the main memory of the
computer. Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved
memory. In general every programming language is containing three
categories of data types.

 Fundamental or primitive data types (int, char, double, float, etc.)


 Derived data types(array, pointer, function, etc)
 User defined data types(structure, enum, union, template, etc)

Primitive data types

These are the data types whose variable can hold maximum one value at
a time, in C++ the following are primitive data types

Type Keyword (data type)


Size

 Charterer char 1byte


 Integer int 2byte
 Float (single precision) float 4byte
 Double(higher precision) double 8byte
 Boolean (true/false) bool 1byte
 Valueless (no value) void……………………….????

C++ Data Types modifiers (built in):


In C++ language Data Type Modifiers are keywords used to change the
properties of current properties of data type (primitive). Data type
modifiers are classified into following types.

• Long

• Short

16 | P a g e
By:-Abdela A.
• Unsigned

• Signed

 As the meaning tells, signed and unsigned modifiers deals with the
(+/-) sign of the variable signed variable stores the signed value in
the allocated memory.
 Unsigned variable does not store signed value. Sign takes 1 bit extra.
So if we are using unsigned value then we can get one bit extra space
to save the value of a variable. The range of values for unsigned types
starts from 0.

Important tips about modifiers

1. All four modifiers can be applied to the int type

2. char type allows only signed and unsigned modifiers

3. double type can be used with the long modifier

4. int type allows use of the shorthand notation. So, the following
variable definitions are identical short int a; and short a; unsigned
int a; and unsigned a; long int a; and long a;

5. The modifiers can be combined. For example, you can


use signed or unsigned with long or short modifiers

Built in data types with their modifiers (size and range)

17 | P a g e
By:-Abdela A.
Variable initialization

Variable initialization is done by using operator "=". Variable initialization


means that you assign a value to this variable: It is the process of
allocating sufficient memory space with user defined values. An
assignment operation assigns, or copies, a value into a variable. You have
also seen that it is possible to assign values to variables when they are
defined. This is called initialization.
When multiple variables are defined in the same statement, it is possible
to initialize some of them without having to initialize all of them
Syntax: Data types Variable
name=Value;

Examples:
18 | P a g e
By:-Abdela A.
 char name=’jawar’;
// This program shows variable initialization and declaration.
 int age=32;
#include <iostream>
#include <string>
using namespace std;
int main()
 flaot GPA=3.75;
{
string month = "February"; month is initialized to "February"//
Operator
int year, //inyear
c++:is not initialized
An =
days operator is a is
28; // days symbol that to
initialized tells
28the compiler to perform specific
year = 2007; // Now
mathematical year ismanipulations.
or logical assigned a value
cout << "In " << year << " " << month << " had " << days << "
days.\n";
return 0;
}

 There are many operators for manipulating numeric values and


performing arithmetic operations.
 C++ provides many operators for manipulating data. Generally, there
are three types of operators: unary, binary, and ternary
 These terms reflect the number of operands an operator
requires. Unary operators only require a single
operand. Binary operators work with two operands. Ternary operators,
as you may have guessed, require three operands.
 An operator is a symbol which tells compiler to take an action on
operands and yield a value. The Value on which operator operates is
called as operands. C++ supports wide verity of operators
 C++ provides different types of operators. These operators can be
used with variables and literals to get the result.
 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
• Compound assignment operator

19 | P a g e
By:-Abdela A.
• Arithmetic operator
• Relational operator
• Logical operator
• Increment/decrement operator
• Bitwise operator
• Misc Operators(this include the following operator)
 Size of()
 Condition? X : Y
 Type casting
 . (dot) and -> (arrow)
 Comma operator(,)

Arithmetic operators (+, -, *, /, %

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 Operator
When we want to modify the value of a variable by performing an
operation on the value currently stored in that variable we can use
compound assignment operators: The assignment operator is used for

20 | P a g e
By:-Abdela A.
storing a value at some memory location (typically denoted by a variable).
Its left operand should be an lvalue, and its right operand may be an
arbitrary expression. The latter is evaluated and the outcome is stored in
the location denoted by the lvalue.

Relational Operator
C++ provides six relational operators for comparing numeric quantities.
Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).

'A' < 'F' // gives 1 (is like 65 < 70)


"HELLO" < "BYE" (string compare)
Logical Operators:
C++ provides three logical operators for combining logical expression. Like the relational
operators, logical operators evaluate to 1 or 0.

Bitwise Operators:
21 | P a g e
By:-Abdela A.
C++ provides six bitwise operators for manipulating the individual bits in an integer
Quantity.

Conditional Operator:
The conditional operator takes three operands. It has the general form:
operand1 ? operand2 : operand3
First operand1 is evaluated, which is treated as a logical condition. If the
result is nonzero then operand2 is evaluated and its value is the final
result. Otherwise, operand3 is evaluated and its value is the final result.
For example:
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
The sizeof Operator
C++ provides a useful operator, sizeof, for calculating the size of any data
item or type. It takes a single operand which may be a type name (e.g.,
int) or an expression (e.g., 100) and returns the size of the specified entity
in bytes. The outcome is totally machine-dependent.
This operator accepts one parameter, which can be either a type or a
variable itself and returns the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type. The
value returned by sizeof is a constant, so it is always determined before
program execution.

Explicit type casting operator:


Type casting operators allow you to convert a datum of a given type to
another. There are several ways to do this in C++. The simplest one,
which has been inherited from the C language, is to precede the
expression to be converted by the new type enclosed between
parentheses (()). There two type of casting

22 | P a g e
By:-Abdela A.
 Explicit casting
 Implicit casting
Syntax: (<data – type> )value; or <data – type> (value);
A value in any of the built-in types we have see so far can be converted
(type-cast) to any of the other types. For example:
 (int) 3.14 // converts 3.14 to an int to give 3
 (long) 3.14 // converts 3.14 to a long to give 3L
 (double) 2 // converts 2 to a double to give 2.0
 (char) 122 // converts 122 to a char whose code is 122
As shown by these examples, the built-in type identifiers can be used as
type operators. Type operators are unary (i.e., take one operand) and
appear inside brackets to the left of their operand. This is called explicit
type conversion. When the type name is just one word, an alternate
notation may be used in which the brackets appear around the operand:
 int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This
happens when values of different types are mixed in an expression. For
example:
 i = i + d; // means: i = int(double(i) + d)
 double d = 1; // d receives 1.0
 int i = 10.5; // i receives 10
Increment/Decrement Operators:
The auto increment (++) and auto decrement (--) operators provide a
Convenient way of, respectively, adding and subtracting 1 from a numeric
variable.
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
– Pre-increment: ++variable
– Post-increment: variable++
– Pre-decrement: --variable
– Post-decrement: variable—

23 | P a g e
By:-Abdela A.
Operator Precedence and associatively (order):
The order in which operators are evaluated in an expression is significant
and is determined by precedence rules. These rules divide the C++
operators into a number of precedence levels Operators in higher levels
take precedence over operators in lower levels.

24 | P a g e
By:-Abdela A.

You might also like