Basic Programming
Basic Programming
Chapter One
Data Mining Project on
“Prediction of Chronic Kidney Disease Using Data Mining Classification
Techniques”
Introduction to Computer Programming
By
Abate Tsegaye
Haramaya University
Chapter Outline
Computer Fundamentals
Language Translators
2
Computer Fundamentals
Introduction
Computer is a device that is used to process data according to a set of
Accept data
Process it(performs computations, and)
Makes logical decisions according to instructions that have been given to
it.
In our current world, computers are almost used in all walks of life for different
purposes.
3
Computer Fundamentals Cont.…
They have been deployed to solve different real-life problems, from the
Storage
4
Computer Fundamentals Cont.…
In order to solve a given problem, computers must be given the correct
want it to do, and then the computer executes the program, following each
step to accomplish the end goal.
5
Computer Fundamentals Cont.…
2. Turn to the right and drive until you reach the second square
7
Computer Fundamentals Cont.…
4. Finally, turn to the right and drive for another 50m and you will see the XY
Campus 9
in front
Computer Fundamentals Cont.…
10
Computer Fundamentals Cont.…
To understand the computer program see the following sample C++
Program:
int a=3;
int b=5;
int c= a+b;
cout<<“the sum of a+b is”<<c;
The above computer program instructs the computer to add to numbers and
display the result on the computer screen
11
The Evolution of Programing Language
Computer programs?
Sets of instructions that control a computer’s processing of data
The instructions that tell the computer what to do
Computer programs (also known as source code) is often written by
professionals known as Computer Programmers
Computer programming?
It is the process of writing, testing, debugging/troubleshooting, and maintaining
the source code of computer programs
Programming Language
It is a computer language used by computer programmers to communicate with
the computer
It is a collection of instructions written using any language like:
C++
Java
Python to perform a specific task
12
Types of Programing Language
A computer program usually consists of two elements:
Data – Characteristics
Code – action
Source code is written in one of the programming languages
Programing language can be defined by
Syntactic(syntax) – It is used to describe the rules that tell you which statements are
High-Level Language
13
Machine language
It was the first language in the evolution of computer programming language
interprets.
It is machine dependent which means that a particular machine language can be
14
Assembly language
It is a programming language that uses mnemonics/ symbols to write a program.
Example:
ADD A, B
SUB A, B
MUL A, B
Low level: each instruction is minimal
mnemonic.
However, no matter how close assembly language is to machine code,
LOAD rate
MULT hours
STOR wages
16
High-level languages
It is a computer language which can be understood by the user
Are more English-like and, therefore, make it easier for programmers to "think"
in the programming language.
It is not machine dependent which means that it can be used in a different machine
with little modifications.
It require less time to write and easier to debug error.
High-level languages also require translation to machine language before
execution.
Compilers translate the entire source code program before execution.
Interpreters translate source code programs one line at a time.
17
High-level languages
Some examples of high-level languages:
FORTRAN (FORmula TRANslator),
BASIC (Beginner’s All-Purpose Symbolic Instruction Code)
PASCAL,
C/C++/C#
Python
Java
JavaScript/PHP.
18
Language Translators
What is a language translator?
It is a software program that translates a program written in assembly language and
source program and the translated machine code is called object code or object
program.
There are 3 types of language translators:
1. Assembler
2. Interpreter
3. Compiler
19
Types of Language Translators
Assembler
It is a software tool that is used to translate assembly language into machine
language
Compiler
It is a language translator software that is used to translate high-level programs into
machine language
When a compiler converts a source program into a machine program it follows the
message, and you have to correct the error based on the program syntax.
20
Compiler Cont.….
If the program is free from any error then the compiler will convert the entire
source program into machine code at once and finally, the program get
executes.
Example:
Instruction 1;
Instruction 2; Translate Machine code
Execute Output
instruction 3;
instruction 4;
Programing languages like c++ and Java uses a compiler for language
conversion
21
The working principle of compiler
Error Fixed
22
Interpreter
It is another type of translator that converts the high-level program into machine
language.
Unlike compilers interpreters convert the source code to machine code line by
23
Interpreter Cont.….
Interpreter displays an error at a time. The programmer should fix that error to
conversion
The working principle of interpreter
24
Algorithm
An algorithm is the sequence of steps to be performed in order to solve a
problem.
In mathematics, computer science, and related fields an algorithm is a finite
25
Algorithm cont.….
Hence, in order to qualify as an algorithm, a sequence of instructions must
possess the following characteristics:
Every instruction should be precise and unambiguous
26
Quality of Algorithm
The following are the primary factors that are frequently used to judge the quality of
an algorithm:
Time Requirement:
To execute any program computer system may require some amount of time
Memory Requirement
To execute any program computer system may require some amount of space
The algorithm performs better when it requires less amount of memory space.
27
Quality of Algorithm Cont.…
Accuracy of solution:
Several algorithms may provide correct solutions to a given problem some of these
28
Programming Paradigm
A programming paradigm is a fundamental style of programming
Unstructured Programming
consisting only of one large (usually main) program
Disadvantages
Complex
if the same statement sequence is needed at different locations within the program,
30
Programming Paradigm
Procedural programming
• We have a single program, which is divided into small pieces called procedures
Advantage
To re-use the same code at different places in the program without copying it
Example
FORTRAN, ADA
31
Programming Paradigm
Object Oriented Programming
• Object-oriented programming is one the new and most powerful paradigms.
• In object-oriented programs, the designer specifies both the data structures and the
instructions.
• Objects can store state information and interact with other objects, but generally
be used, the desired result, and the procedure to be used to produce the result.
• The procedure, or solution, selected is referred to as an algorithm.
• There are three commonly used tools to help to document program logic (the
33
Pseudocode
• Pseudocode is a compact and informal high-level description of a computer algorithm that
uses the structural conventions of programming languages, but typically omits details
such as subroutines, variables declarations and system-specific syntax.
• It is a simpler version of a programming code in plain English which uses short phrases to
34
Pseudocode
Example1:
Original Program Specification: Write a pseudocode for a program that obtains
two integer numbers from the user and print out the sum of those numbers.
Pseudocode:
Prompt the user to enter the first integer
Display an output prompt that explains the answer as the sum Display the result
35
Pseudocode
Example 2: Write a pseudocode to find the largest of two numbers by accepting
numbers from the user and printing out the largest one.
BEGIN
NUMERIC nNum1,nNum2
DISPLAY "ENTER THE FIRST NUMBER : "
INPUT nNum1
DISPLAY "ENTER THE SECOND NUMBER : "
INPUT nNum2
IF nNum1 > nNum2
DISPLAY nNum1 + " is larger than "+ nNum2
ELSE
DISPLAY nNum2 + " is larger than " + nNum1
END
36
Pseudocode
Exercise:
Write a pseudocode for a program that obtains one integer number from
the user and prints out the square of the number.
37
Flowchart
A flowchart (also spelled flow-chart and flow chart) is a schematic representation
of an algorithm or a process.
The advantage of a flowchart is it doesn’t depend on any particular programming
processes.
The following table shows some of the common symbols.
38
Flowchart
39
Flowchart
Example 1: - Draw flow chart of an algorithm to add two numbers and display
their result.
40
Flowchart
Example 2: Draw flow chart of an algorithm that check whether a number is
negative or not.
41
Flowchart
Example 3: Write the algorithmic description and draw a flow chart to find the
following sum.
• Sum = 1+2+3+…. + 50
42
System Development Life Cycle (SDLC)
The Systems Development Life Cycle (SDLC) is a conceptual model used in
project management that describes the stages involved in a computer system
development project from an initial feasibility study through maintenance of the
completed application.
The phases of SDLC are discussed below briefly:
43
Feasibility study
The first step is to identify a need for the new system.
Organizational Feasibility Technical Feasibility
How well the proposed system supports the Hardware, software, and network
strategic objectives of the organization? capability, reliability, and availability
Testing
Unit Testing
Integrating Testing
System Testing
Maintenance
What happens during the rest of the software's life: changes, correction,
additions, and moves to a different computing platform and more.
This, the least exciting and perhaps most important step of all, goes on
46
seemingly forever.
Thank y u…!
Chapter Two
Data Mining Project on
“Prediction of Chronic Kidney Disease Using Data Mining Classification
Fundamentals of C++Techniques” Programming Languages
Chapter Outline
A brief history of C++
Input/output in C++
Comments in C++
C++ tokens
Operator
2
A Brief History of C++
C++ language was developed by Bjarne Stroustrup AT & T bell laboratory in early
1980’s
This C++ was mainly developed with the help of two languages (Simula 67 and C)
3
What is C++
C++ is a general purpose programming language and it support various
Procedural
languages such as
Java
C#
6
Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you
may be using a commercial text editor or word processor that can produce text
files.
The important thing is that whatever you write your program in, it must save
simple, plain-text files, with no word processing commands embedded in the text.
Examples of safe editors include Windows Notepad, the DOS Edit command,
7
Compiling
How you invoke your compiler, and how you tell it where to find your source
After your source code is compiled, an object file is produced. This file is often
named with the extension .OBJ. This is still not an executable program.
To turn this into an executable program, you must run your linker.
8
Linking
C++ programs are typically created by linking together one or more OBJ files
9
Basic Structure of C++ programming
A program in C++ is divided into 3 sections:
1. Standard Libraries Section
2. Main Function Section
3. Function Body Section
demonstrate.
The preprocessor reads throughout your source code, looking for lines that begin with the pound
symbol (#), and acts on those lines before the compiler runs.
The angle brackets (<) around the filename tell the preprocessor to look in all the usual places
screen. 11
Main Function Section
int main(){}
On line 3
All c++ programs have a main function. main is followed by a pair of parenthesis ()
because it is a function.
In general, a function is a block of code that performs one or more actions.
When your C++ program is executed by the computer, the operating system call this main
function.
main(), like all functions, must state what kind of value it will return.
The return value type for main() in hello.CPP is int, which means that this function
All functions begin with an opening brace ({) and end with a closing brace (}).
Function Body Section
{
cout<<“Hello World!”;
return 0;
}
The body of a function is the thing that found in between the opening and closing
braces
Everything between the opening and closing braces is considered a part of the
function.
• The object cout is used to print a message (strings and values) to the screen.
• Here's how cout is used: type the word cout, followed by the output redirection
operator (<<).
• Whatever follows the output redirection operator is written to the screen.
13
Cont.…
Line 6: return 0;
The return instruction causes the main() function to finish, and return the code that
the instruction is followed by in our case 0.
The return keyword tells the program to return a value (in our case 0) to the
function int main().
After the return statement execution control return to the operating system
component, that launched this program.
This is most usual way to terminate a program that has not found any errors during
its execution.
14
Key Note
The C++ program has been structured in different lines in order to be more
readable, but it is note compulsory to do so
For Example:
int main()
{
cout<<“Hello World!”;
return 0;
}
We could have written
int main() { cout<<“Hello World!”; return 0; }
15
Key Note
The C++ program is a collection of functions. The pervious example contains only
one function which is main().
As usual, execution begins at main().
Every C++ program must have a main().
In C++ the separation between instructions is specified with an ending
semicolon(;) after each one.
The C++ statements terminate with semicolon.
16
17
Basic Data Types in C++
Therefore, we can use them directly to declare entities like variables and
constants.
We can also call the primitive data types as pre-defined data types or standard
data types.
In c++ there are different primitive(built-in) data types.
18
Basic Data Types in C++
Integer(int)
Integer is a data type that is used in c++ programming to store only integer
data types.
20
Basic Data Types in C++
Float (float) and Double(double)
float and double are used to store floating-point numbers (numbers with decimal
21
Basic Data Types in C++
Character (char)
Character is a data type that is used in c++ programming to store characters like
In c++ integer(ASCII value) is stored in a char variable rather than the character
itself.
22
Basic Data Types in C++
For example, when you store a character value using char data types what you get
stored is not the character but the binary equivalent of ASCII Value of the
character.
Example: char x=‘A’;
Here the binary equivalent of A which is 65 is stored in the x variable rather than
the character itself because the ASCII value of ‘A’ is 65.ASCII - Binary Character
Table and ASCII Table
char data type could be signed and unsigned
logical values.
Boolean variable has two possible values 0 and 1 where 0 represents Boolean
24
Comments
A comment is a piece of descriptive text which explains some aspect of a
program.
Program comments are totally ignored by the compiler and are only intended
25
Input/ Output in C++
C++ includes libraries that provide several ways for performing input and
output
Input stream: when bytes flow from the device(for example a keyword) to
the user and cout object with insertion operator (<<)for printing outputs to the
screen.
26
Basic Elements
Tokens
Token is the smallest unit of a program written in any language
It the source program text that the compiler does not break into component
element.
The keyword, identifiers, variables, constants, strings and operators are example
of tokens.
punctuation characters such as brackets [], braces {}, parentheses (), and
Keywords
Constants Variables
28
Keywords (reserved words)
Reserved/Keywords have a unique meaning within a C++ program.
These symbols, the reserved words, must not be used for any other purposes.
29
Identifiers
Identifiers are names given to a variable, arrays, functions, classes or other
an identifier is not recommended though, because many library functions in C++ use
such identifiers. Similarly, the use of two consecutive underscore symbols _ _, is
forbidden
The following are valid identifiers
C++ is case-sensitive. That is lower-case letters are treated as distinct from upper-
case letters. Thus the word NUM different from the word num or the word Num.
31
Variables
A variable is a symbolic name for a memory location in which data can be
computations in a program.
All variables have two important attributes:
33
Variable Declaration
Declaring a variable means defining (creating) a variable.
You create or define a variable by stating its type, followed by one or more
spaces, followed by the variable name (it should be a valid identifier), and a
semicolon(;).
34
Rules for Naming a Variable
1. A variable name can only have alphabets(a-z or A-Z), numbers(0-9) and
the underscore(_) symbol.
2. A variable name cannot begin with a number
3. It is preferred to begin the variable name with a lowercase character (for
example age is preferable to Age)
4. A variable name can start with an underscore. However, it’s not considered
a good practice.
5. A variable name cannot be keywords.
35
Creating More Than One Variable at a Time
You can create more than one variable of the same type in one statement by
writing the type and then the variable names, separated by commas.
For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
keep in mind that you cannot mix types in one definition statement.
36
Assigning Values to Your Variables
You assign a value to a variable by using the assignment operator (=). Thus, you
int Width = 5;
You can initialize more than one variable while you declare. For example:
37
Constant
A constant is a memory location in which values can be stored. Unlike a variable, its
value can not be changed or modified after its definition. It means once we define a
variable as a constant in a program its value will be fixed and never be changed.
Example: const int a=50;
a=60 // which displayed an error message
If we try to change the value of a constant type variable, it shows an error message
Exercise: Create a c++ program to find the area of a circle using const
keyword
Area= π*r*r
40
Operators
In c++ operators is a symbol that tells the compiler to perform certain mathematical
and logical manipulation and C++ provides different types of operators such that:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
conditional operators and
Miscellaneous operators.
41
Assignment Operators
The assignment operator is used for storing a value at some memory location
following table
42
Arithmetic Operators
C++ provides five basic arithmetic operators. These are summarized in the table
below
43
Increment/decrement Operators
The auto-increment (++) and auto-decrement (--) operators provide a convenient
44
Relational Operators
C++ provides six relational operators for comparing numeric quantities.
45
Logical Operators
C++ provides three logical operators for combining logical expression.
Logical negation is a unary operator, which negates the logical value of its single operand. If
integer quantity.
These are summarized in the table below.
47
Precedence of Operators
The order in which operators are evaluated in an expression is significant and is
These rules divide the C++ operators into a number of precedence levels.
48
49
Cont..
For example,
in 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 using brackets. For example, rewriting the
above expression as a == (b + c) * d
(char) 122 or char (122) // converts 122 to a char whose code is 122
51
Cont.…
In some cases, C++ also performs an implicit type conversion. This happens when
values of different types are mixed in an expression. For example:
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to
double (promoted) and then added to d.
The result is a double which does not match the type of i on the left side of the
assignment, so it is converted to int (demoted) before being assigned to i.
52
Thank y u…!
Chapter Three
Data Mining Project on
“Prediction of Chronic Kidney Disease Using Data Mining Classification
ControlTechniques”
statements
Chapter Outline
Conditional Statements
The if statement
Looping Statements
The ‘while’ Statement
Other Statements
The ‘Continue’ Statement
Branching statements are used for specifying alternate paths of execution, depending on the
3
Introduction Cont.…
Specifying the order in which statements (actions) execute in a program is called
program control.
Program control or control statement can be :
Conditional (Selection) Statement (if, if…else, switch)
4
Conditional Statement
If Statement:
It is sometimes desirable to make the execution of a statement dependent upon a
if (expression)
statement;
For Example
if (count != 0)
average = sum / count;
5
If Statement Cont.…
To make multiple statements dependent on the same condition, we can use a
compound statement:
For Example :
if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
6
If else statement
A variant form of the if statement allows us to specify two alternative statements:
One which is executed if a condition is satisfied and one which is executed if the
9
If else statement Cont.…
A frequently-used form of nested if statements involves the else part
10
Switch Statement
The switch statement provides a way of choosing between a set of alternatives,
Switch (expression)
{
Case constant 1:
block of statement;
break;
Case constant 2:
block of statement;
break;
default :
block of statements;
11
}
Switch Statement Cont.…
The first expression (called the switch tag) is evaluated, and
The outcome is compared to each of the numeric constants (called case labels),
in the order they appear, until a match is found.
12
Switch Statement Cont.…
For example
suppose we have parsed a binary arithmetic operation into its three components
and stored these in variables operator, operand1, and operand2. The following
switch statement performs the operation and stores the result in the result
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
} 13
Exercise - Conditional Statements
1. Write an if-else statement that outputs the word High if the value of the variable score is
greater than 100 and Low if the value of score is less than100. The variable score is of
type int.
2. Write an if-else statement that outputs the word Passed provided the value of the variable
exam is greater than or equal to 60 and also the value of the variable programsDone is
greater than or equal to 10. Otherwise, the if-else statement outputs the word Failed. The
variables exam and programsDone are both of type int.
3. Write a program that accept a number(1-12) from user and display the name of the month.
Hint use switch statement(1-september,2-october,3-November,4-December,5-January,6-
February,7-march,8-April,9-may,10-June,11-July,12-august)
14
Looping Statements
The ‘while’ Statement:
The while statement (also called while loop) provides a way of repeating a
15
The while’ Statement Cont.…
The while’ Statement:
For example, suppose we wish to calculate the sum of all numbers from 1 to 10.
For example, removing the first and the third expression gives us something
identical to a while loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; something;
Removing all the expressions gives us an infinite loop.
21
The ‘do…while’ Statement Cont.…
For example, suppose we wish to repeatedly read a value and print its square, and
stop when the value is zero.
This can be expressed as the following loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
22
Exercise -Looping Statements
1. Write a program is to display 1 up to 10 horizontally(i.e separated by tab ‘\t’
as well as vertically use the endline ‘\n’ or endl
2. Write a program is to find the factorial of 10!.
3. Write a program is to display the reverse of a given number for example if a
user inters 965 the program should display 569.
4. Write a program that print sum of the digits. For instance if a user enters 123
the program should display 6 i.e 1+2+3=6
23
Branching Statements
The ‘continue’ Statement:
The continue statement terminates the current iteration of a loop and instead jumps to
while loop) and is particularly useful when you want to skip over certain iterations of
a loop based on a certain condition.
The syntax of the continue statement is simple. When the continue statement is
executed inside a loop, the control jumps to the end of the current iteration, and the
next iteration of the loop starts.
24
Example of the continue statement
25
Example of the continue statement
int i=0;
while(i<=10)
{
if(i==5)
{
i++;
continue;
}
cout<<i<<" ";
i++;
}
The output will be 0 1 2 3 4 6 7 8 9 10
26
Branching Statements
The ‘break’ Statement:
The break statement in C++ is used to terminate the loop or switch statement
it is placed in.
When executed, the break statement causes the program to exit the loop or
27
Example of the break statement
for (int i = 0; i < attempts; ++i)
{
cout << "Please enter your password: ";
cin >> password;
if (password==123)
{
cout <<“your password is correct”;
break;
}
cout << "Incorrect password please try again!\n";
}
28
Example of the break statement
int i=0;
while(i<=10)
{
if(i==7)
{
cout<<"the loop is terminated here";
break;
}
goto label;
where the label is an identifier that marks the jump destination of goto.
The label should be followed by a colon and appear before a statement within the same
30
Example of goto Statements
int main()
{
char x;
again:
cout <<"\nHellow Information Systems Students!";
cout<<"\nDo you want to print Hellow Information Systems Students again [Y/N]:";
cin>>x;
if(x=='y'||x=='Y')
{
goto again;
}
cout<<endl << "Good bye!";
return 0;
31
}
Branching Statements
The ‘return’ Statement :
The return statement enables a function to return a value to its caller.
return expression; where expression denotes the value returned by the function.
The type of this value should match the return type of the function.
32
Branching Statements
The ‘return’ Statement:
For a function whose return type is void, expression should be empty: return;
The only function we have discussed so far is main, whose return type is always
int.
The return value of main is what the program returns to the operating system
33
Thank y u…!
Chapter Four
Data Mining Project on
“Prediction of Chronic Kidney Disease Using Data Mining Classification
Array andTechniques”
Strings in C++
Chapter Outline
Array
Introduction to Array
Advantage of Array
Multi-dimensional arrays
2
Introduction to Array
An array is a derived data type that is constructed with the help of a primitive data
type
It stores multiple values in a single variable with continuous memory location but
the value that stores in a single variable should have the same data type.
The syntax of the array:
subscript).
3
Introduction to Array Cont.…
The index must be an integer and indicates the position of the element in the array.
10 21 19 34 25
0 1 2 3 4
Arrays in C++ are zero-bounded; that is the index of the first element in the array
is 0 and the last element is N-1, where N is the size or the length of the array.
4
Advantage of Array
5
Declaration of Array
Like a regular variable an array must be declared before it is used.
Length of array (which is always enclosed in square brackets []), specifies how
many of these elements the array has to contain and the number of elements must
be an integer.
6
Example
#include <iostream.h>
int main()
{
int arr1[5];
Output
arr1[0]=90;
arr1[1]=50;
arr1[2]=20;
arr1[3]=40;
arr1[4]=10;
for(int i=0;i<5;i++)
{ cout<<"Array["<<i<<"]\t"<<arr1[i]<<endl; }
7
}
Example
For example, data on the average temperature over the year in Ethiopia for each of
the last 10 years could be stored in an array declared as follows:
float annual_temp [10];
From this example, we can understand that
This declaration will cause the compiler to allocate space for 10 consecutive float
variables in memory
8
Declaration of Array Cont.…
It is best to make the array size a constant and then, if required, the program can
be changed to handle a different size of the array by changing the value of the
constant.
const int NE = 100;
float annual_temp[NE];
It would not work if an ordinary variable was used for the size in the array
declaration since at compile time the compiler would not know a value for it.
9
Initialization of Array
An array can be initialized in a similar manner to a variable.
For example initializing an array to hold the first few prime numbers could be
written as follows:
int primes[ ] = {1, 2, 3, 5, 7, 11, 13};
If the array is given a size then this size must be greater than or equal to the
elements.
10
Accessing array element
The first element in an array always has the index 0, and if the array has n
used:
annual_temp[2] = 1.5; Note that since the first element is at index 0, then the
ith element is at index i-1.
Hence in the above the 3rd element has index 2.
11
Accessing array element
A value can be read into an array element directly, using cin
13
Copying arrays
Loop to do copying, one element at a time
for (int i = 0 ; i < SIZE; i++)
x[i] = y[i];
This code will copy the elements of array y into x, overwriting the original
contents of x.
A loop like this has to be written whenever an array assignment is needed.
14
TYPES OF ARRAY
Single dimensional array
15
Multi-dimensional arrays
An array may have more than one dimension.
Therefore a two dimensional array has two subscripts, a three dimensional array
represents the eight rows, and the other dimension represents the eight columns.
Syntax : Data Type Multi_arrayName [ ] [ ];
16
Multidimensional arrays Cont.…
Example double sales[ 10][ 5] ;
The above example declares a two-dimensional array sales of 10 rows and 5
columns, in which every component is of type double. As in the case of a one-
dimensional array, the rows are numbered 0. . . 9 and the columns are numbered 0. . .
4
17
Declaring Multidimensional Arrays
Initialize a multi-dimensional array, you must assign the list of values to array
elements in order, with the last array subscript changing while the first subscript
holds steady.
The first three elements go int the Array[0]; the next three into the Array[1]; and so forth.
as shown below.
int theArray [5][3] ={{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15} };
The compiler ignores the inner braces, which clarify how the numbers are
distributed.
Each value should be separated by comma, regardless of whether inner braces are
include.
The entire initialization must set must appear within braces, and it must end with a
semicolon.
19
Omitting the Array Size
If a one-dimensional array is initialized, the size can be omitted as it can be found
Note however:
20
Accessing array component
To access the components of a two-dimensional array, you need a pair of indices:
21
Example 1
#include <iostream> s[1][1]=55;
// write this code and practice by Output
s[2][0]=333;
your self
s[2][1]=88;
using namespace std;
int main() //Access Two dimensional array
s[1][0]=44;
Example 2
#include <iostream>
using namespace std;
int main(){
int twodros[3][2]={23,34,46,56,67,89};
int sum=0;
for(int i=0;i<3;i++){
for(int j=0;j<2;j++){
sum=sum+twodros[i][j];
}
}
cout<<"Sum = "<<sum<<endl;
}
23
Strings Representation
and
Manipulation
24
Introduction to String
String is nothing but a sequence of characters in which the last character is the
Any array of characters can be converted into string type in C++ by appending
25
Strings representation
For example, a string variable s1 could be declared as follows:
char s1[10];
The string variable s1 could hold strings of length up to nine characters since
initialized.
For example:
char s1[] = "example";
char s2[20] = "another example"
26
Strings representation
would store the two strings or array of characters as follows:
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
Note that the length of a string does not include the terminating null character.
27
String output
A string is output by sending it to an output stream, for example:
28
String Input
When the input stream cin is used space characters, newline etc. are used as
cannot start with leading spaces, also if it has a space character in the middle
then input will be terminated on that space character.
29
String Input
To read a string with several words in it using cin we have to call cin once for
each word.
For example to read in a name in the form of a First_name followed by a
this situation. This argument specifies the character that tells the function to stop
reading.
The default value of this argument is the newline('\n')character, but if you call
the function with some other character for this argument, the default will be
overridden by the specified character.
32
String Input
In this example, we call the function with a dollar sign ('$') as the third argument
//reads multiple lines, terminates on '$' character
#include<iostream.h>
int main(){
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<“\n You entered:\n"<<str; }
33
Strings Manipulation
String constants
You can initialize a string to a constant value when you define it. Here's an
example
#include <iostream.h>
int main(){
char str[] = "Welcome to C++ programming language";
cout<<str;
}
34
Strings Manipulation
Copying string with strcpy() or strncpy() function
strcpy() or strncpy() function are used to copy the content of one string into
another
You can copy strings using the strcpy or strncpy function.
We assign strings by using the string copy function strcpy.
To use these functions first we have to include the string.h. header file
strcpy(destination, source);
strcpy copies characters from the location specified by source to the location
specified by destination.
It stops copying characters after it copies the terminating null character.
The return value is the value of the destination parameter.
35
Strings Manipulation
Copying string with strcpy() function
You must make sure that the destination string is large enough to hold all of the
characters in the source string (including the terminating null character).
Example:
#include <iostream.h>
#include <string.h>
int main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return 0;
}
36
Strings Manipulation
There is also another function strncpy, which is like strcpy, except that it copies
only a specified number of characters.
strncpy(destination, source, int n);
strncpy( ) function may not copy the terminating null character.
37
Strings Manipulation
Example
#include <iostream.h>
#include <string.h>
int main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
} 38
Strings Manipulation
Concatenating strings with strcat () or strncat() function
In C++ the + operator cannot normally be used to concatenate string, as it can in
some languages such as BASIC; that is you can't say: str3 = str1 + str2;
You can use strcat() or strncat
Strcat() function concatenate the source string at the end of the target string
The function strcat concatenates (appends) one string to the end of another string.
strcat(destination, source);
39
Strings Manipulation
Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1,"ABCD");
cout << str1 << endl;
strcat(str1,"EFGH");
cout <<str1<<endl;
char str2[] = “XYZ";
strcat(str1, str2);
cout << str1 << endl;
return 0;
}
40
Strings Manipulation
The function strncat is like strcat except that it copies only a specified number of
characters.
strncat(destination, source, int n);
It may not copy the terminating null character.
41
Strings Manipulation
Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
return 0;
}
42
Strings Manipulation
Comparing strings using strcmp() function
Strings can be compared using strcmp or strncmp functions
Strcmp() function used to compares two strings to find out whether they are some
or different.
strcmp(str1, str2);
strcmp returns: < 0 if str1 is less than str2
= 0 if str1 is equal to str2
> 0 if str1 is greater than str2
43
Strings Manipulation
Example:
#include <iostream.h>
#include <string.h>
int main(){
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
return 0;
44
}
Strings Manipulation
The function strncmp is like strcmp except that it compares only a specified
number of characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating null character has been
found in one of the strings.
45
Strings Manipulation
Example:
#include <iostream.h>
#include <string.h>
int main(){
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
return 0;
} 46
Other String Functions
strlen()
this function count number of character in the string(it will return the length of
the string)
strupr()
This function converts the string into upper case format.
strlwr()
This function converts the string into lower case format.
strrev()
This function converts the string into reverse string.
47
Thank y u…!