0% found this document useful (0 votes)
6 views121 pages

Computer Programmming in C++

Uploaded by

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

Computer Programmming in C++

Uploaded by

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

1

2
3
4
5
Define the Problem
 After careful reading, the problem should be divided into three
separate
component
 Input
○ Data provided to the problem
 Output
○ What is required from the solution
 Processing
○ List of actions needed to produce the required
output
6 Design the Solution

There are more than 1 ways to do that but we will use a graphical approach
which will involve usage of Geometrical Shapes
to represent different kinds of steps in a solution
7
8 Step-2: Design the Solution

Start by drawing a “Start” symbol

 Show a symbol for Input


 Show process symbol(s) for processing
 There can be more than 1 such steps depending on the complexity of the problem
Show a symbol for Output
Finish by drawing a “Stop” Symbol
9
10
11
12
13
14
15 Introduction to Problem Solving
16 6:The Algorithmic Language (Pseudo code)
 During development of an algorithm, the language gradually progresses from
English towards a programming language notation.
 An intermediate notation called pseudocode is commonly used to express
algorithms.
 The Pseudo code is neither an algorithm nor a program. It is an abstract form
of a program.
 It is defined for an algorithm. It does not use any graphical representation. In
pseudo code, the program is represented in terms of words and phrases, but
the syntax of program is not strictly followed.
 Advantages:
 Easy to read,
 Easy to understand,
How to write Pseudocode

17
 An algorithm can be written in pseudo code using six (6) basic computer
operations:
 A computer can receive information.
 Typical pseudocode instructions to receive information are:
 Read name
 Get name
 Read number1, number2
 A computer can output (print) information.
 Typical pseudocode instructions are:
 Print name
 Write "The average is", avg
18
How to write Pseudocode(Cont…)
 A computer can perform arithmetic operation
 Typical pseudocode instructions:
 Add number to total, or
 Total = Total + Number
 Avg = sum/total
 A computer can assign a value to a piece of data:
 e.g. to assign/give data an initial value:
 Initialize total to zero
 Set count to 0
 To assign a computed value:
 Total = Price + Tax
 A computer can compare two (2) pieces of information and select one of two actions.
Typical pseudocode e.g.
19 IF number < 0 then
add 1 to neg_number
ELSE
add one to positive number
end-if
 A computer can repeat a group of actions.
Typical pseudocode e.g.
REPEAT until total = 50
read number
write number
add 1 to total
end-repeat
OR
WHILE total < = 50 do:
read number
write number
end-while
Algorithmic Structure
20

 Every algorithm should have the following sections, in the stated


order:
 Header : Algorithm’s name or title.
 Declaration : A brief description of algorithm and variables.
i.e. a statement of the purpose.
 Body : Sequence of steps
 Terminator : End statement
21 WRITE AN ALGORITHM TO FIND THE
SUM OF TWO NUMBERS.
STEP 1 : START
STEP 2 : ACCEPT FIRST NUMBER
STEP 3 : ACCEPT SECOND NUMBER
STEP 4 : ADD THESE TWO NUMBERS
STEP 5 : DISPLAY RESULT
STEP 6 : STOP
22 WRITE AN ALGORITHM TO FIND THE
SUM OF THREE NUMBERS.
STEP 1 : START
STEP 2 : ACCEPT ALL THREE NUMBERS
STEP 3 : ADD ALL THREE NUMBERS AND
STORE IN ONE VARIABLE
STEP 4 : DISPLAY THE RESULT
STEP 5 : STOP
23 WRITE AN ALGORITHM TO FIND THE
AREA OF RECTANGLE.
STEP 1 : START
STEP 2 : ACCEPT THE W OF RECTANGLE
STEP 3 : ACCEPT THE H OF RECTANGLE
STEP 4 : Area = w × h
STEP 5 : DISPLAY
STEP 6 : STOP
24
BASICS OF PROGRAMMING
 Language: A system of communication used by a particular country or
community.
 Computer Language: A programming language is a vocabulary and set of
grammatical rules for instructing a computer or computing device to
perform specific tasks.
 The term programming language usually refers to high-level languages,
such as BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and Pascal.
 Program: A computer program is a collection of instructions that performs
a specific task when executed by a computer.
 A computer program is usually written by a computer programmer in a
programming language.
25 Types of Computer Languages
26 Translator Software
 A computer will not understand any program written in a language, other
than its machine language.
 The programs written in other languages must be translated into the
machine language.
 Such translation is performed with the help of software.
 Types of Translator Software
 Assembler: A program which translates an assembly language program into
a machine language program is called an assembler.
 Compiler: It is a program which translates a high level language program
into a machine language code.
 A compiler takes the whole program and convert it into machine code. So it is
faster than interpreter.
27 Translator Software(Cont…)
 Interpreter: An interpreter is a program which is also used to translates
high level language instructions into machine code.
 It translates only one statement of the program at a time.
 It reads only one statement of program, translates it and executes it.
 Then it reads the next statement of the program again translates it and
executes it.
 On the other hand, a compiler goes through the entire program and then
translates the entire program into machine codes.
 A compiler is 5 to 25 times faster than an interpreter. By the compiler, the
machine codes are saved permanently for future reference.
 On the other hand, the machine codes produced by interpreter are not
saved. An interpreter is a small program as compared to compiler.
 It occupies less memory space, so it can be used in a smaller system which
28 C & C++ Languages
 C was created by Dennis Ritchie, AT&T Bell Labs in 1970sC
 C++ was created by Bjarne Stroustrup, Bell Labs
 C++ is procedural
 C++ is superset of C
 C++ directly supports object-oriented and generic programming
 C++ maintains efficiency of C
 Application domains:
 Systems software, application software, device
drivers, embedded software, high-performance server and client
applications, entertainment software such as video games, native code
for Android applications.
29 Writing C++ Program
 C++ Program is written in IDE(Integrated Development Environment).
 IDE is a text editor which is used to write source code and compile them
 Different IDE,s are available like Dev C++, Borland C++ and Turbo C++.
 Code written in IDE is called source code with extension .CPP.
 After compilation it is object code with extension .obj.
 After running its called executable code with extension .EXE.
Program Compilation Process
30
31 Program Compilation Process
32
Types of Error in C++
 Error is an abnormal condition and whenever it occurs execution of the program is
stopped. These are mainly classified into following types.
 Compile time error or Syntax error
 If any error is generated at the time of compilation is known as compile time error.
 A syntax error is an error in the syntax of a coding or programming language, entered
by a programmer. Syntax errors are caught by compiler. E.g. missing semicolon at end of
statements.
 Runtime Error or Logical error
 An error that occurs during the execution of a program.
 E.g division by zero
33 C++ Character Set
 Character set is a set of valid characters that a language can recognise. A character
represents any letter, digits, or any other sign.
 C++ has the following character set :
 Letters : A-Z, a-z
 Digits : 0-9
 Special Symbols : Space + - ∗ ⁄ ^ \ ( ) [ ] { } = != < > . ′ ″ $ , ; : % ! & _ # <= >= @
 White Spaces : Blank space, Horizontal tab (→), Carriage return ( ↵), Newline, Form
feed.
 Other Characters : C++ can process any of the 256 ASCII characters as data or as
literals.
34 Tokens in C++
Tokens are the smallest meaningful chunk(symbols or words) of program that have meaning to the
compiler.
Token type Description/Purpose Examples
Keywords or Reserve Words int, double, for, auto
Words withspecial meaningto the
compiler
Identifiers cout, std, x, myFunction
Names of things that are not built into
the language
Literals Basic constant values whose value is "Hello, world!", 24.3, 0, ’c’
specified directly in the source code

Operators +, -, &&, %, <<


Mathematical or logical operations

Punctuation/Separators {}(),;
Punctuation defining the structure of a
program
Whitespace
Spaces of various sorts; ignored by the
Spaces, tabs, newlines, comments
compiler
Identifiers
35  A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to 9).
 C++ does not allow punctuation characters such as @, $, and % within identifiers.
 C++ is a case-sensitive programming language.
 The rules of naming identifiers in C++ :
1. C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different
2. The first character must be alphabit. However, Underscore can be used as first character while
declaring the identifier.
3. Only alphabetic characters, digits and underscore (_) are permitted in C++ language for
declaring identifier.
4. Other special characters are not allowed for naming a variable / identifier
5. Keywords cannot be used as Identifier.
36 Variable
 A variable is a temporary container to store information, it is a named location in
computer memory where varying data like numbers and characters can be stored
and manipulated during the execution of the program".
 For Example
 int my_Age;
 int my_Salary;
 int _employee;
 Variable attributes
 A variable in a programming language represents a storage location. In C++,
each variable has six attributes, name, address, type, value, scope and the storage
class.
37 Constants in C++
 A constant in C++ means an unchanging value and each constant has a type but does not
have location except the string constant.
 Integer Constants
 Integer constants consist of one or more digits such as 0,1,2,3,4 or -115. Floating point
constants contain a decimal point such as 4.15, -10.05. It can also be written in scientific
notation such as 1E-35 means 1*10^-35 or -1E35 means 1*10^35.
 Character Constants
 Character constants specify the numeric value of that particular character such as ‘a’ is the
value of a
 String Constants
 String constants consist of characters enclosed in double quotes such as
 “Hello, World”
 The string is stored in the memory and the numeric value of that constant is the address of this
memory. The string constant is suffixed by ‘\0’, (the null character) by the compiler.
Comments
38

 Comments are portions of the code ignored by the compiler which allow the user to make
simple notes in the relevant areas of the source code. Comments come either in block form
or as single lines.
 Single-line comments (informally, C++ style), start with // and continue until the end of
the line. If the last character in a comment line is a \ the comment will continue in the next
line.
 Multi-line comments (informally, C style), start with /* and end with */.

•Reserve Words:
 A reserved word is a word that cannot be used as an identifier, such as the
name of a variable, function, or label – it is "reserved from use".

 They are reserved because they have been pre-assigned a specific meaning within that
programming language, thus the compiler recognizes those words to mean a specific
thing or action. Within C++ the reserved words are also known as "keywords".
e.g void, main, int etc….
39 C++ Data Types
C++ data Types

Builtinn Derived Void

Unionn Pointer
Array

Float Double
char integer
40 Basic Data Types

Several of the basic types can be modified using one or more of these typemodifiers:
 signed
 unsigned
 short
 long
41 Basic Data Types
a. Character data: Any character of the ASCII character set can be considered as a character data
types and its maximum size can be 1 byte or 8 byte long. ‘Char’ is the keyword used to
represent character data type in C++. Char - a single byte size, capable of holding one
character.
b. Integer data: The keyword ‘int’ stands for the integer data type in C++ and its size is
either 2 or 4 bytes. The integer data type can again be classified as
1. Long int - long integer with more digits
2. Short int - short integer with fewer digits.
3. Unsigned int - Unsigned integer
4. Unsigned short int – Unsigned short integer
5. Unsigned long int – Unsigned long integer
c. Floating point data: - The numbers which are stored in floating point representation with
mantissa and exponent are called floating point (real) numbers. These numbers can be declared as
‘float’ in C++. float – Single – precision floating point number value.
d. Double data : - Double is a keyword in C++to represent double precision floating point
numbers.
42
43 Delimiters
 This is symbol that has syntactic meaning and has got significance. These will not specify
any operation to result in a value.
44 Operators
 An Operator is a symbol that operates on a certain data type. The data items that operators act upon
are called operands.
 Unary operator: Operates on single operand, e.g Increment operator.
 Binary Operators: Operates on two operands, e.g Arithmetic operator.
 Ternary Operators: Operates on three operands, e.g conditional operator.
 operators can be classified into various categories based on their utility and action.
 1. Arithmetic Operators
 2. Relational Operators
 3. Logical Operator
 4. Assignment Operator
 5. Increment & Decrement Operator
 6. Conditional Operator
 7. Bitwise Operator
 8. Comma Operator
45 1. Arithmetic Operators
The Arithmetic operators performs arithmetic operations. The Arithmetic operators can
operate on any built in data type. A list of arithmetic operators are

Operator Meaning

+ Addition

- Subtraction

*
Multiplication

/ Division

% Modulo
division
2. Relational Operators
46
Relational Operators are used to compare arithmetic, logical and character expressions. The Relational
Operators compare their left hand side expression with their right hand side expression. Then evaluates to
an integer. If the Expression is false it evaluate to “zero”(0) if the expression is true it evaluate to “one”.

Operator Meaning

< Less than

> Greater than

<= Less than or Equal to

>= Greater than or Equal to

== Equal to

!= Not equal to
3. Logical Operators
47  A logical operator is used to evaluate logical and relational expressions. The logical operators act upon
operands that are themselves logical expressions. There are three logical operators, Operators Expression
 (i) && Logical AND
 (ii) || Logical OR
 (iii) ! Logical NOT
 (i) Logical And (&&): A compound Expression is true when two expression when two expressions are
true. The && is used in the following manner.
Exp1 && Exp2.
 The result of a logical AND operation will be true only if both operands are true.
 The results of logical operators are:
 Exp1 Op. Exp2: Result
 True && True True
 True && False False
 False && False False
 False && True False
 Example: a = 5; b = 10; c = 15;
 Exp1 && Exp2 Result
 1. ( a< b ) && ( b < c ) => True
48 3. Logical Operators
 (ii) Logical OR: A compound expression is false when all expression are false otherwise the compound
expression is true. The operator “||” is used as It evaluates to true if either exp-1 or exp-2 is true. The truth
table of “OR” is
 Exp1|| Exp2
 Exp1 Operator Exp2 Result:
 True || True True
 True || False True
 False || True True
 False || False False
 Example: a = 5; b = 10; c = 15;
 Exp1 Exp2 Result
 1. ( a< b ) || ( b < c ) => True
 2. ( a> b ) || ( b < c ) => True
 3. ( a< b ) || ( b > c ) => True
 4. ( a> b ) || ( b > c ) => False
49 3. Logical Operators
 (iii) Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to true(1)
if the expression is false (0) or it evaluates to false (0) if expression is true (1). The general
form of the expression.
 ! ( Relational Expression )
 The truth table of NOT :
 Operator. Exp1 Result
 ! True False
 ! False True
 Example: a = 5; b = 10; c = 15
 1. !( a< b ) False
 2. !( a> b ) True
4. Assignment Operator
50  An assignment operator is used to assign a value to a variable. The most commonly used assignment
operator is =. The general format for assignment operator is : <Identifer> = < expression >
Where identifier represent a variable and expression represents a constant, a variable or a
Complex expression. If the two operands in an assignment expression are of different data types,
then the value of the expression on the right will automatically be converted to the type of the identifier
on the left.
 Example: Suppose that I is an Integer type Variable then
 1. I = 3.3 3 ( Value of I )
 2. I = 3.9 3 ( Value of I )
 3. I = 5.74 5 ( Value of I )
 Multiple assignment
 < identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>;
 Example: a,b,c are integers; j is float variable
 1. a = b = c = 3;
 2. a = j = 5.6; then a = 5 and j value will be 5.6
51 Compound Assignment Operator
 The combination of Arithmatic operator and Assignment operator is called compound
assignment operator.
 1. += e.g x+=10 can be written x=x+10
 2. -= e.g x-=10 can be written x=x-10
 3. *= e.g x*=10 can be written x=x*10
 4. /= e.g x/=10 can be written x=x/10
 5. %= e.g x%=10 can be written x=x%10
52 5. Increment & Decrement Operator
 The increment/decrement operator act upon a Single operand and produce a new value is
also called as “unary operator”. The increment operator ++ adds 1 to the operand and the
Decrement operator – subtracts 1 from the operand.
 Syntax: < operator >< variable name >;
 The ++ or –- operator can be used in the two ways.
 Example : ++ a; Pre-increment (or) a++ Post increment —a; Pre-
 Decrement (or) a— Post decrement
 1. ++ a Immediately increments the value of a by 1.
 2. a ++ The value of the a will be increment by 1 after it is utilized.
53 6. Conditional operator (or) Ternary operator (? :)
 It is called ternary because it uses three expressions. The ternary operator acts like If- Else
construction.
 The conditional operator consists of 2 symbols the question mark (?) and the colon (:) The
syntax for a ternary operator is as follows.
 exp1 ? exp2 : exp3
 Example:
 1. a = 5 ; b = 3;
 ( a> b ? cout (“a is larger”) : cout(“b is larger”));
 Output is :a is larger
54 Decision Making Statement

 Decision making statement is depending on the condition block need to be executed or not
which is decided by condition.
 If the condition is "true" statement block will be executed, if condition is "false" then
statement block will not be executed.
 In C++ language there are three types of decision making statement.
 if
 if-else
 switch
55 Decision Making Statement

 if-then Statement
 if-then is most basic statement of Decision making statement. It tells to program to execute
a certain part of code only if particular condition is true.
 Syntax
 If(condition)
{ .......... .......... }
56 Decision Making Statement
57 Decision Making Statement

 Example
 #include<stdio.h>
#include<conio.h>
void main()
{ int time=10;
clrscr();
if(time>12)
{ cout<<"Good morning"; }
getch();
 }
58 Decision Making Statement

 Constructing the body of "if" statement is always optional, Create the body when we are
having multiple statements.
 For a single statement, it is not required to specify the body.
 If the body is not specified, then automatically condition part will be terminated with next
semicolon ( ; ).
59 Decision Making Statement

 if-else statement
 In general it can be used to execute one block of In the above syntax whenever
statement among two blocks, in C language if and else condition is true all the if block
are the keyword in C. statement are executed remaining
 Syntax statement of the program by
neglecting else block statement. If
if(condition) the condition is false else block
statement remaining statement of
{ ........ statements ........ }
the program are executed by
Else neglecting if block statements.
{ ........ statements ........ }
60 Decision Making Statement
61 Decision Making Statement

/* Program to check whether an integer is


positive or negative This program considers 0 else
as positive number */
{ cout << "You entered a negative integer: "
#include <iostream;
<< number << endl; }
int main()
cout << "This line is always printed.";
{ int number;
}
cout << "Enter an integer: ";
cin >> number;
if ( number >= 0)
{ cout << "You entered a positive integer: "
<< number << endl; }
62 Decision Making Statement

Nested if...else
 The if...else statement executes two different codes depending upon whether the test expression is true or false.
Sometimes, a choice has to be made from more than 2 possibilities.
 The nested if...else statement allows you to check for multiple test expressions and execute different codes for
more than two conditions.
 Syntax of Nested if...else
if (testExpression1)
{ // statements to be executed if testExpression1 is true }
else if(testExpression2)
{ // statements to be executed if testExpression1 is false and testExpression2 is true }
else if (testExpression 3)
{ // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true }
else { // statements to be executed if all test expressions are false }
63 Decision Making Statement

/* Program to check whether an integer is else if (number < 0)


positive, negative or zero*/
{ cout<<"You entered a negative integer: “
#include <iostream> int main() << number << endl; }
{ int number; else
cout << "Enter an integer: "; { cout << "You entered 0." << endl; }
cin >> number; cout << "This line is always printed.";
if ( number > 0) }
{ cout << "You entered a positive integer: "
<< number << endl;
}
64 Decision Making Statement

 Switch Statement
 A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and
string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
65 Decision Making Statement

 Rules for apply switch


 With switch statement use only byte, short, int, char data type.
 You can use any number of case statements within a switch.
 Value for a case must be same as the variable in switch .
 Limitations of switch
 Logical operators cannot be used with switch statement. For instance
 Example
 case k>=20: //is not allowed
 Switch case variables can have only int and char data type. So float data type is not
allowed.
66 Decision Making Statement
67 Decision Making Statement

 Example of Switch case ase 4: cout<<"Today is Thursday";


 #include<iostream.h> #include<conio.h> break;

 void main() case 5: cout<<"Today is Friday";

 break;
{ int ch;
case 6:
 clrscr();
cout<<"Today is Saturday";
 cout<<"Enter any number (1 to 7)";
break;
 cin>>ch;
case 7: cout<<"Today is Sunday";
 switch(ch)
break;
 { case 1: cout<<"Today is Monday"; break; default: cout<<"Only enter value 1 to 7";
 case 2: cout<<"Today is Tuesday"; } getch();
 break; }
 case 3: cout<<"Today is Wednesday";  Output
 break;  Enter any number (1 to 7): 5 Today is Friday
68 LOOPS

 Control Flow Statement


 Set of instructions given to the compiler to execute set of statements until condition
becomes false is called loops. The basic purpose of loop is code repetition that means same
code repeated again and again.
 Why use Loop
 Where need repetition of same code a number of times at that place use Loop in place of
writing more than one statements. The way of the repetition will be forms a circle that's
why repetition statements are called loops.
69 LOOPS

 Types of Loops.
 There are three type of Loops available
in 'C' programming language.
 while loop
 for loop
 do-while
70 LOOPS

 While loop
 In while loop First check the condition if
condition is true then control goes inside
the loop body other wise goes outside
the body. while loop will be repeats in
clock wise direction.
 Syntax
while(condition)
{ Statements; ............
Increment/decrement (++ or --);
}
71 LOOPS

#include<iostream.h>
#include<conio.h>
Output:
void main() 1
{
int i; clrscr(); 2
i=1;
while(i<5)
3
{ cout<<endl<<i;
4
i++;
}
getch();
}
72 LOOPS

 do-while in C++
 A do-while loop is similar to a while loop, except
that a do-while loop is execute at least one time.
 A do while loop is a control flow statement that
executes a block of code at least once, and then
repeatedly executes the block, or not, depending on
a given condition at the end of the block (in while).
Syntax
Do
{ Statements;
Increment or Decrements (++ or --)
}
while(condition);
73 LOOPS

#include<iostream.h> #include<conio.h>
Output
void main()
{ int i;
1
clrscr(); 2
i=1;
3
do { cout<<endl<<i; i++; }
while(i<5); 4
getch();
}
74 LOOPS

 For Loop in C++


 When you need to execute a block of code several
number of times then you need to use looping concept
in C++ language. In C++ Programming Language for
loop is a statement which allows code to be
repeatedly executed. For loop contains 3 parts.
 Initialization
 Condition
 Increment or Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}
75 LOOPS

 Initialization: step is execute first and this is


execute only once when we are entering into
the loop first time. This step is allow to declare
and initialize any loop control variables.
 Condition: is next step after initialization step,
if it is true, the body of the loop is executed. If
it is false, the body of the loop does not
execute and flow of control goes outside the
for loop.
 Increment or Decrements: After completion
of Initialization and Condition steps loop body
code is executed and then Increment or
Decrements steps is execute. This statement
allows to update any loop control variables.
76 LOOPS

#include<stdio.h> #include<conio.h> Output


void main() 1
{ int i; 2
clrscr();
3
for(i=1;i<5;i++)
4
{
cout<<endl<<i;
}
getch();
}
77 Array in C++ Language

 Array in C++ Language


 An array is a collection of similar data
type value in a single variable. It is a
derived data type in C++, which is
constructed from fundamental data type
of C++ language.
78 Array in C++ Language

 Advantage of array  Declaring Array


 Code Optimization: Less code is required, one  To declare an array in C++ required type of
variable can store numbers of value. array elements and size of array.
 Easy to traverse data: By using array easily
Syntax
retrieve the data of array.
 Datatype arrayName[SIZE];
Easy to sort data: Easily short the data using
swapping technique  Initializing Array
 Random Access: With the help of array index you
can randomly access any elements from array.  Initializing is a process to initialize
 Dis-Advantage of array the value in array variable. This is
 Fixed Size: Whatever size, we define at the time of happen in two ways, initialize
declaration of array, we can not change their size, if
you need more memory in that time you can not
array one by one or all elements
increase memory size, and if you need less memory are initializing once.
in that case also wastage of memory.
79 Array in C++ Language

 Initialization of array one by one  Initialization of array at once


 int arr[5]; //decleration  int arr[] //decleration
arr[0]=10;
arr[1]=20; arr[]={10,20,30,40,50};
arr[2]=30;
arr[3]=40;
arr[4]=50;
80 Array in C++ Language

 Accessing Array Elements in C++  xample of Array in C++


 We can access array elements with the  #include<iostream.h> #include<conio.h>
help of index value of element.  void main()
Output  {
 int i, marks[]={80, 62, 70, 90, 98}; clrscr()
80  for(i=0;i<5;i++)
62  { cout<<endl<<marks[i];

70  }
 getch();
90
 }
98
81 Array in C++ Language

C++ Program to Copy all elements of an array into for(i=0;i<n;i++)


Another array {
#include <iostream> cin>>list[i];
using namespace std; }
int main() for(i=0;i<n;i++)

{ {
list2[i]=list[i];
Int list[100],list2[100];
}//programology content
int n;
cout<<"copied array "<<endl;
int i,j;
for(i=0;i<n;i++)
cout<<" enter number till you wanna copy "<<endl;
cin>>n; cout<<list2[i]<<endl;
cout<<" enter list programology conetnt"<<endl; }
82 Array in C++ Language

 C++ Program to Sort Elements of Array in  for(j=0;j<10;j++)


 { cout<<a[j]; }
Ascending Order
 for(i=0;i<=10;i++)
 #include<iostream.h>
 {
 #include<conio.h>  for(j=0;j<=10-i;j++)
 void main()  { if(a[j]>a[j+1])

 {  { temp=a[j]; a[j]=a[j+1];
 a[j+1]=temp;}
 int i,a[10],temp,j;
 }
 clrscr(); }
 cout<<"Enter any 10 num in array:\n";  cout<<"\nData after sorting: "; for(j=0;j<10;j++)

 for(i=0;i<=10;i++)  {cout<<a[j];}
 getch(); }
 { cin>>a[i]; }
 Enter any 10 num in array: 2 5 1 7 5 3 8 9 11 4
 cout<<"\nData before sorting: "; Data After Sorting: 1 2 3 4 5 7 8 9 11
83 Array in C++ Language

 2-dimentional array  Syntax


 In 2-dimentional elements are arranged in row  Datatype ArrayName[SIZE][SIZE];
and column format.
 When we are working with 2-dimentional array  int a[MAX_ROWS][MAX_COLS];
we require to refer 2-subscript operator which 
indicates row and column sizes.
Initialization of 2D Array
 The main memory of 2-dimentional array is rows  There are two ways to initialize a two
and sub-memory is columns. Dimensional arrays during declaration.
 On 2-dimentional array when we are referring  int disp[2][4] = { {10, 11, 12, 13}, {14, 15,
one-subscript operator then if gives row address,
2-subscript operator will gives element. 16, 17} };
 On 2-dimentional array arrayName always gives  int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16,
main memory that is 1st row base address, 17};
arrayName will gives next row base address.
84 String in C++
Declaration of string
Strings are declared in C in similar manner as arrays. Only
difference is that, strings are of char type.
 String in C++
 String is a collection of character or
group of character, it is achieve in C
language by using array character. The
string in C language is one-dimensional
array of character which is terminated by
a null character '\0'. In other words string
is a collection of character which is
enclose between double cotes ( " " ).
85 String in C++

 Important points for Declaration of  In declaration of the string size must be


string unsigned integer value (not -ve or zero
 value) which is greater than zero only.
In declaration of string size must be
required to mention otherwise it gives an  Example
error.  char str[]; // Invalid
 Syntax  char str[0]; // Invalid
 char str[]; // Invalid  char str[-1]; // Invalid
 char str[10]; // Valid  char str[10]; // Valid
86 String in C++

 Syntax
 char variable_name[SIZE];
 Char Example
 char str[]="abcd";
Initializing Array string
OR
 According to array initialization concept char str[5]="abcd";
 str[5]; OR
char str[5]={'a','b','c','d','\0'};
OR
char str[]={'a','b','c','d','\0'};
OR
char str[5]={'a','b','c','d','\0'};
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

You might also like