[go: up one dir, main page]

0% found this document useful (0 votes)
3 views181 pages

Basic Programming

The document outlines a data mining project focused on predicting chronic kidney disease using classification techniques, as part of a computer programming course at Haramaya University. It covers computer fundamentals, programming languages, algorithms, and the system development life cycle (SDLC). The content includes explanations of programming paradigms, language translators, and problem-solving techniques, along with examples and flowcharts.

Uploaded by

mohaomarm491
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)
3 views181 pages

Basic Programming

The document outlines a data mining project focused on predicting chronic kidney disease using classification techniques, as part of a computer programming course at Haramaya University. It covers computer fundamentals, programming languages, algorithms, and the system development life cycle (SDLC). The content includes explanations of programming paradigms, language translators, and problem-solving techniques, along with examples and flowcharts.

Uploaded by

mohaomarm491
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/ 181

Haramaya University

COLLEGE OF COMPUTING AND INFORMATICS


DEPARTMENT OF SOFTWARE ENGINEERING

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

 Evolution of programing language

 Language Translators

 Algorithm, pseudo code, flow chart

 System Development Life Cycle (SDLC)

2
Computer Fundamentals
Introduction
 Computer is a device that is used to process data according to a set of

instructions and is capable of performing Arithmetic and Logical operations.


 It is a general-purpose machine able to

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

simplest game playing app to complex nuclear energy production.


Program

Input Process Output

Storage
4
Computer Fundamentals Cont.…
 In order to solve a given problem, computers must be given the correct

instruction about how they can solve it.


 In a computer program, you tell a computer step by step exactly what you

want it to do, and then the computer executes the program, following each
step to accomplish the end goal.

5
Computer Fundamentals Cont.…

1. Go straight and you will find the first square


6
Computer Fundamentals Cont.…

2. Turn to the right and drive until you reach the second square
7
Computer Fundamentals Cont.…

3. Turn to the left and go for 50m


8
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

legal or accepted by the programming language and which are not.


 Semantic - The rules which determine the meaning of the instructions.

Programming languages can be divided into two major categories:


 Low-Level Language

 High-Level Language
13
Machine language
 It was the first language in the evolution of computer programming language

 It is the only language that the computer can understand directly

 Machine language, is a sequence of 0s and 1s that the computer reads and

interprets.
 It is machine dependent which means that a particular machine language can be

used on only one type of computer.


Example:
1000011100001101010

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

 Assembly language is nothing more than a symbolic representation of machine

code, which allows the symbolic designation of memory locations.


 In assembly language, instruction is an easy-to-remember form called a

mnemonic.
 However, no matter how close assembly language is to machine code,

computers still cannot understand it. 15


Assembly language
• The instructions first have to be translated into machine language. A program called an

assembler translates the assembly language instructions into machine language(object

code). Some examples of instructions in assembly language and their corresponding

machine language code.

• You can calculate the weekly wages as follows:

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

high-level language to a machine program.


 A program written in assembly and high-level language is called source code or

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

syntax rule of the programming language


 If an error is present in a program the compiler can't fix it rather it displays an error

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

Compile Compiler Translate Machine Execute


Source Program Output
code

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

line and execute them directly without any further conversion.


Example:
Translate Execute
instruction 1; Machine code Output
Translate Execute
instruction 2; Machine code Output
instruction 3; Translate Machine code Execute Output
instruction 4; Translate Machine code Execute Output

23
Interpreter Cont.….
 Interpreter displays an error at a time. The programmer should fix that error to

interpret the next line.


 Programming languages like Python and PHP uses an interpreter for language

conversion
The working principle of interpreter

Translate Interpreter Execute Executable code


Source Program i.e. Machine code

Get next instruction Error Fixed

24
Algorithm
 An algorithm is the sequence of steps to be performed in order to solve a

problem by the computer is known as an algorithm.


 It is a step-by-step description of how to arrive at the solution to the given

problem.
 In mathematics, computer science, and related fields an algorithm is a finite

sequence of steps expressed for solving a problem.


 Algorithms are used for calculation, data processing, and many other fields.

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

 Each instruction should be such that it can be performed in a finite time.

 One or more instructions should not be repeated infinitely.

 After the algorithm terminates the desired results must be obtained.

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

 The algorithm performs better when it requires less 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

may provide more accurate results than others.


 As a result, we must select the best algorithm based on the accuracy of the solution.

28
Programming Paradigm
A programming paradigm is a fundamental style of programming
Unstructured Programming
 consisting only of one large (usually main) program

 “main program”' stands for a sequence of commands or statements

data is global throughout the whole program

Disadvantages
 Complex

 if the same statement sequence is needed at different locations within the program,

the sequence must be copied


29
Programming Paradigm
Procedural programming
 Based upon the concept of a procedure call

 A procedure call is used to invoke the procedure

 Procedures (routines, subroutines, methods, functions) simply contain a series of

computational steps to be carried out to solve a problem

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

 Easier way to keep track of program flow

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

types of operations that can be applied to those data structures.


• This pairing of a piece of data with the operations that can be performed on it is

known as object-oriented programming.


• A program thus becomes a collection of cooperating objects, rather than a list of

instructions.
• Objects can store state information and interact with other objects, but generally

each object has a distinct, limited role.


32
Problem solving Techniques
• Before a program is written, the programmer must clearly understand what data are to

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

algorithm). These are flowcharts, structured chart, and pseudo code.

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

write code for a program before it is implemented in a specific


• The purpose of using pseudocode is that it may be easier for humans to read than

conventional programming languages, and that it may be a compact and


environment-independent generic description of the key principles of an
algorithm.

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

Prompt the user to enter a second integer

Compute the sum of the two user inputs

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

language, so that it can be used, to translate an algorithm to more than one


programming language.
 Flowchart uses different symbols (geometrical shapes) to represent different

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:

 Feasibility study  Implementation

 Requirements analysis  Testing

 Designing solution  Maintenance

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

Economic Feasibility Operational Feasibility


End user acceptance
 Cost savings
Management support
 Increased revenue
Customer, supplier, and government
 Decreased investment
requirements
 Increased profits
44
Requirements analysis : is the process of analyzing the information needs of the
end users, the organizational environment, and any system presently being used,
developing the functional requirements of a system that can meet the needs of the
users.
Designing solution:
 After the requirements have been determined, the necessary specifications for
the hardware, software, people, and data resources, and the information products
that will satisfy the functional requirements of the proposed system can be
determined.
 The design will serve as a blueprint for the system and helps detect problems
before these errors or problems are built into the final system.
45
Implementation
The real code is written here. Systems implementation is the construction of the new
system and its delivery into production or day-to-day operation.

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++

 Structure of C++ program

 Basic datatypes in 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)

 Initially C++ was known as ‘C with Classes’ and

letter renamed as C++ in 1983’s

 After that several modification were done on C++

 Finally in 1990 ANSI published as a new programming language and technology

3
What is C++
 C++ is a general purpose programming language and it support various

programming paradigm such as


Object-oriented

Procedural

Functional and so on.


 It is used to program computer to perform a specific tasks

 Specialized software is used to manage the task of developing programs in

particular converting the program written in its programming language to


binary form which is understood by a computer.
4
Why we learn is C++
 Because of its performance, C++ is used to create games, desktop

applications, operating systems, browsers and other applications.


 After learning C++ it will be much easier to learn other programming

languages such as
Java

C#

Python and so on.


 C++ enables you to understand a computer internal architecture as well as

how computer stores and retrieve data.


5
C++ IDE
The complete development cycle in C++ is:

Write the program,

compile the source code,

 link the program,

and run it.

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,

EMACS, and VI (for Linux).


 The files you create with your editor are called source files, and for C++ they

typically are named with the extension .CPP

7
Compiling

 Your source code file can't be executed, or run, as a program can.

 To turn your source code into a program, you use a compiler.

 How you invoke your compiler, and how you tell it where to find your source

code, will vary from compiler to compiler.

 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

with one or more libraries.


 A library is a collection of linkable files that were supplied with your compiler

that you purchased separately, or that you created and compiled.


 All C++ compilers come with a library of useful functions (or procedures) and

classes that you can include in your program.


 A function is a block of code that performs a service, such as adding two

numbers or printing to the screen. A class is a collection of data and related


functions.

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

For example, the following is a very basic C++ program:


1: //This is simple C++ Program with hello.cpp file name
2: # include <iostream.h>
3: int main()
4: {
5: cout<<“Hello World!”;
6: return 0;
7: }
10
cont.…
 The first line of the above program is the comment which describes what the program going to

demonstrate.

Standard Libraries Section


On line 2
 #include or the # symbol, which is a signal to the preprocessor.
 Each time you start your compiler, the preprocessor is run.

 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

for this file.


 The file iostream.h (InputOutput-Stream) is used by cout, which assists with writing to the

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 program starts, main() is called automatically.

 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

will return an integer value.


12

 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++

Basic or primitive data types in c++


 Primitive data types are the built-in data types that c++ languages provide.

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

values. Example: -100, -10, 0, 69, 200, etc.…


 In c++ the int keyword is used to define an integer

Syntax: int age; where age is variable


 Depending on the compiler version you are running an integer data type may

require a 2 or 4 bytes size.


 Its range is

From -32768 to 32767 for 2 byte of memory or

From -2147483648 to 2147483647 for 4 byte of memory


19
Basic Data Types in C++
 The modifiers signed, unsigned, short, and long may be applied to integer basic

data types.

Types Byte Range


int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
long int 2 -2147483648 to 2147483647
unsigned short int 0 to 65535

20
Basic Data Types in C++
Float (float) and Double(double)
 float and double are used to store floating-point numbers (numbers with decimal

points). Example: 77.8 and 3.1415


 float is 4 bytes in size while double is 8 bytes.

Syntax: float Hight; or double Hight; where Hight is variable.

Types Byte Range


float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 304E-4932 to 1.1E+4932

21
Basic Data Types in C++
Character (char)
 Character is a data type that is used in c++ programming to store characters like

letters and punctuation marks.


 In c++ the char keyword is used to define a character.

Syntax: char Name; where Name is variable.


 The char data type has a 1-byte (8-bit) size

 Characters in c++ are enclosed inside a single quotes ‘ ’.

 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

Types Byte Range


unsigned char 1 0 to255
signed char 1 23 -128 to 127
Basic Data Types in C++
Boolean (bool)
 Boolean is a data type that is used in c++ programming to store Boolean or

logical values.
 Boolean variable has two possible values 0 and 1 where 0 represents Boolean

values false and 1 represents Boolean value true.


 In c++ the bool keyword is used to define Boolean

Syntax: bool x=false; or where x is variable.


 Booleans are used in conditional statements and loops.

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

for human readers.


 C++ provides two types of comment delimiters:

 Single Line //……………………………

 Multi Line /*…………………………….*/

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

main memory this process is called input operation.


output stream: when bytes flow from the main memory to a display device

this process is called output operation.


In c++ we use the cin object with extraction operator (>>) to take inputs from

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 is the smallest element of a program that is meaningful to the compiler

 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

commas (,) are also tokens.


27
C++ Tokens

Keywords

Operators C++ Identifiers


Tokens

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.

 All reserved words are in lowercase letters.

The following are some of the reserved words of C++.

29
Identifiers
 Identifiers are names given to a variable, arrays, functions, classes or other

entities by the programmer. A function identifier is an identifier that is used to


name a function.
 An identifier must:

 Start with a letter or underscore


 Consist only of letters, the digits 0-9, or the underscore symbol _
 Not be a reserved word
 Identifiers can be short names like x, y, and z or descriptive names like age,

height, and sum but it is strongly recommended to use descriptive names to


create understandable and maintainable code.
30
Example int age=25; or int x=25;
Identifiers Cont.….
 The underscore symbol _, is considered to be a letter. Its use as the first character in

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

The following are invalid:

 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

stored and subsequently recalled.


 Variables are used for holding data values so that they can be utilized in various

computations in a program.
 All variables have two important attributes:

 A type: e.g. integer, float, character

 A value: e.g. 234, 234.24, ‘A’

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(;).

Datatype Variable name ;


Eg. int age;

 Variables must be declared before used

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

would assign 5 to Width by writing


int Width; //declare Width
Width = 5; //assign value to Width
 You can combine these steps and initialize Width when you define it by writing

int Width = 5;
 You can initialize more than one variable while you declare. For example:

int width = 5, length = 7;

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

in the program and you must initialize a constant when it is created.


const int x=100;// correct but const int x; x=100;//incorrect
 Constants can be any of the basic data types like integer, float-point, character, string

and Boolean values


38
How to define constant in C++
In c++ we can define constant into ways
1. By using #define preprocessor
2. By using a const keyword
Creating Constant using # define preprocessor
 It is used to define constant globally
 Syntax: #define variable_name value
 Example: #define PI 3.145
Exercise: Create a c++ program to find the area of a circle using
#define preprocessor
Area= π*r*r
39
How to define constant in C++
Creating Constant using a const keyword
 With the const prefix you can declare constants with a specific type in the
same way as you would do with a variable
 Syntax: const datatype variable_name = inial_value;
 Example: const float PI =3.145;

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

(typically denoted by a variable).


 The shorthand arithmetic and bitwise assignment operators are summarized in the

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

way of, respectively, adding and subtracting 1 from a numeric variable.


 These are summarized in the following table. The examples assume the

following variable definition:


Example: int k = 5;

44
Relational Operators
 C++ provides six relational operators for comparing numeric quantities.

 These are summarized in table below.

 Relational operators evaluate to 1 (representing the true outcome) or 0

(representing the false outcome).

45
Logical Operators
 C++ provides three logical operators for combining logical expression.

 These are summarized in the table below.

 Like the relational operators, logical operators evaluate to 1 or 0.

Operator Name Example


! Logical Negation !(5==5) //gives 0
&& Logical And 5 < 6 && 6 <6 //gives 0
|| Logical Or 5 <6 || 6 <5 // gives 1

 Logical negation is a unary operator, which negates the logical value of its single operand. If

its operand is nonzero it produces 0, and if it is 0 it produces 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.


46
Bitwise Operators
 C++ provides six bitwise operators for manipulating the individual bits in an

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

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.

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

 Causes + to be evaluated before *.


50
Simple Type Conversion
A value in any of the built-in types we have seen so far can be converted (type-cast)
to any of the other types. For example:

(int) 3.14 or int (3.14) // converts 3.14 to an int to give 3

(double) 2 or double (2) // converts 2 to a double to give 2.0

(char) 122 or char (122) // converts 122 to a char whose code is 122

(unsigned short) 3.14 or unsigned short (3.14) // gives 3 as an unsigned short

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

 The if else statement

 The switch statement

 Looping Statements
 The ‘while’ Statement

 The ‘for’ Statement

 The ‘do…while’ Statement

 Other Statements
 The ‘Continue’ Statement

 The ‘break’ Statement

 The ‘goto’ Statement


2
 The ‘Return’ Statement
Introduction
Like many other procedural languages, C++ provides different forms of statements
for different purposes.
 Declaration statements are used for defining variables.

 Assignment statements are used for simple, algebraic computations.

 Branching statements are used for specifying alternate paths of execution, depending on the

outcome of a logical condition.


 Loop statements are used for specifying computations, which need to be repeated until a certain

logical condition is satisfied.


 Flow control statements are used to divert the execution path to another part of the program.

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)

Looping (Repetition )Statement(while, do…while, for-loop)

Branching Statement(break, continue, return)

4
Conditional Statement
If Statement:
 It is sometimes desirable to make the execution of a statement dependent upon a

condition being satisfied.


 Syntax:

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

condition is not satisfied.


 The general form:
if (expression)
{
statement1;
}
else
{
statement2;
} 7
If else statement Cont.…
 First expression is evaluated.
 If the outcome is nonzero (true) then the statement1 is executed. Otherwise,
statement2 is executed
For example:
if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
else {
interest = balance * debitRate;
balance += interest;
}
8
If else statement Cont.…
 If statements may be nested by having an if statement appears inside another if
statement.
For example:
if (callHour > 6)
{
if (callDuration <= 5)
charge = callDuration * tarrif1;
else
charge = 5 * tarrif1 + (callDuration - 5) * tarrif2;
}
else
charge = flatFee;

9
If else statement Cont.…
 A frequently-used form of nested if statements involves the else part

consisting of another if-else statement.


For example:
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special;

10
Switch Statement
 The switch statement provides a way of choosing between a set of alternatives,

based on the value of an expression

 The general form of the switch statement is:

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.

Statements following the matching case are then executed.

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

statement while a condition holds. It is one of the three flavours of iteration in


C++.
 The general form is:
while (expression) or while (expression){
statement; Statement1;
Statement2;
}

15
The while’ Statement Cont.…
The while’ Statement:
 For example, suppose we wish to calculate the sum of all numbers from 1 to 10.

 This can be expressed as:


#include<iostream.h>
int main()
{
int i = 1,sum = 0;
while (i <= 10)
{
sum += i;
i++;
}
cout<<“the sum of 1 up to 10 is =“ << sum;
return 0; 16
}
The ‘for’ Statement
The for statement (also called for loop) which is used in C++ to repeat the execution of a

code, instead of repeating the code again and again.


The syntax of for loop in C++ has 3 parts

for(initialization; condition; updation)


{
statement;
}
Example : for (int i=1;i<=10;i++)
{
cout << “Hello IS”<<endl;
}
17
The general for loop is equivalent to the following while loop:
initialization;
while (condition) {
statement;
updation; }
for example, calculates the sum of all integers from 1 to n.
#include<iostream.h>
int main()
{
int sum = 0;
for(int i=1; i <= 10; i++)
{
sum += i;
}
cout<<“the sum of 1 up to 10 is =“ << sum;
return 0; 18
}
The ‘for’ Statement Cont…

 Any of the three expressions in a for loop may be empty.

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.

 This loop's condition is assumed to be always true:

for (;;) // infinite loop


something;
19
The ‘for’ Statement Cont.…
 For loops with multiple loop variables are not unusual. In such cases, the comma
operator is used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;
 Because loops are statements, they can appear inside other loops. In other words,
loops can be nested.
For example
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << “(“ << i << “,” << j << “)\n”;
20
The ‘do…while’ Statement
The do statement (also called do loop) is similar to the while statement, except that
its body is executed first and then the loop condition is examined.
The general form of do…while:
do or do{
statement; statements;
while (expression); }while(expression);

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

the next iteration.


The continue statement is commonly used inside loops (for loop, while loop, do-

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

for(int i = 0; i<=10; i++)


{
if(i==5)
{
continue;
}
cout <<“The value of i =“ << i << “, ”;
}
Here the output will be 0, 1, 2, 3, 4, 6, 7, 8, 9, 10

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

switch and continue executing code after the loop or switch.


It is an error to use the break statement outside a loop or a switch.

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;
}

cout << i<<" ";


i++;
}
The output will be 0 1 2 3 4 5 6 the loop is terminated here
29
Branching Statements
The ‘goto’ Statement:
The goto statement provides the lowest level of jumping.

It has the general form:

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

function as the goto statement itself.

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.

It has the general form:

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

when it completes its execution.

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

 Declaration and Initialization of Array

 Accessing array element

 Multi-dimensional arrays

 Strings Representation and Manipulation

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:

Data Type Variable Name [Length of array];


Example: int age[5];
 An individual element of an array is identified by its own unique index (or

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

 Thus the elements of an array are ordered by the index.

 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

 Arrays can store a large number of values with a single name.

 Arrays are used to process many values easily and quickly.

 The values stored in an array can be sorted easily.

 The search process can be applied on arrays easily.

5
Declaration of Array
 Like a regular variable an array must be declared before it is used.

 A typical declaration for an array in C++ is:

Data Type Variable Name [Length of array];


Where
Data Type is a valid data type (like int, float...)

Variable Name is a valid identifier (like grade, salary ….)

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

number of elements in the initialization list. For example:


int primes[10] = {1, 2, 3, 5, 7};
 would reserve space for a ten element array but would only initialize the first five

elements.
10
Accessing array element
 The first element in an array always has the index 0, and if the array has n

elements the last element will have the index n-1.


 An array element is accessed by writing the name of the array followed by the

subscript in square brackets.


 Thus to set the 3rd element of the array above to 1.5 the following assignment is

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

cin >> count[i];


 The element can be increased by 5,

count[i] = count[i] + 5; or, using the shorthand form of the assignment


count[i] += 5;
 Array elements can form part of the condition for an if statement, or indeed,

for any other logical expression:


if (annual_temp[j] < 10.0)
cout << "It was cold this year " << endl;
12
Copying arrays
 The assignment operator cannot be applied to array variables:
const int SIZE=10;
int x [SIZE] ;
int y [SIZE] ;
x=y; // Error - Illegal
 Only individual elements can be assigned to using the index operator,

e.g., x[1] = y[2];.


 To make all elements in 'x' the same as those in 'y' (equivalent to assignment), a

loop has to be used.

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

 Multi dimensional array

15
Multi-dimensional arrays
 An array may have more than one dimension.

 Each dimension is represented as a subscript in the array.

 Therefore a two dimensional array has two subscripts, a three dimensional array

has three subscripts, and so on.


 Arrays can have any number of dimensions, although most of the arrays that you

create will likely be of one or two dimensions.


 A chessboard is a good example of a two-dimensional array. One dimension

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 syntax of a multi-dimensional array looks like this:


Data Type Variable Name [Length of array] [Length of array];
int theArray[5][3];

 The first three elements go int the Array[0]; the next three into the Array[1]; and so forth.

 The program initializes this array by writing:

int theArray[5][3]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15};


18
Initializing multidimensional arrays
 But for the sake of clarity, the program could group the initializations with braces,

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

from the number of initializing elements:


int x[] = { 1, 2, 3, 4} ;
 This initialization creates an array of four elements.

 Note however:

int x[][] = { {1,2}, {3,4} } ; // error is not allowed.


 and must be written

int x[2][2] = { {1,2}, {3,4} } ;

20
Accessing array component
 To access the components of a two-dimensional array, you need a pair of indices:

 one for the row position and

 one for the column position.

 The syntax to access a component of a two-dimensional array is:


arrayName[ indexExp1][ indexExp2];
Example: theArray [0][2]; =3

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

{ for(int i=0;i<3;i++){ // for rows

int s[3][2]; //two dimensional for(int j=0;j<2;j++){


array declaration
cout<<"Array "<<s[i][j]<<endl; }
// initializing two dimensional
}
array
return 0;
s[0][0]=23;
s[0][1]=34; }
22

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

null character ‘\0’.


 The null character indicates the end of the string.

 Any array of characters can be converted into string type in C++ by appending

this special character at the end of the array sequence.


 Syntax of string

Data Type String Name[string size];


char StringName[ ];

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

space is needed for the final null character.


 Strings can be initialized at the time of declaration just as other variables are

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:

cout << "The string s1 is " << s1 << endl;


 would print

The string s1 is example

28
String Input
 When the input stream cin is used space characters, newline etc. are used as

separators and terminators.


 Thus when inputting numeric data cin skips over any leading spaces and

terminates reading a value when it finds a white-space character (space, tab,


newline etc. ).
 This same system is used for the input of strings, hence a string to be input

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

Last_name we might use code as follows:


char firstname [12], lastname[12];
cout << "Enter name ";
cin >> firstname ;
cin >> lastname;
cout << "The name entered was "
<< firstname << " "
30
<< lastname;
String Input
To read text containing blanks we use another function, cin.get(string name, size ).
#include<iostream.h>
int main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string:";
cin.get(str , max); // max avoid buffer overflow
cout<<"\n You entered : "<<str;
}
31
String Input
Reading multiple lines
 We have solved the problem of reading strings with embedded blanks, but what

about strings with multiple lines?


 It turns out that the cin. get() function can take a third argument to help out in

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…!

You might also like