0% found this document useful (0 votes)
20 views102 pages

Pamir Us First Semester 1

Uploaded by

saeedafghan01234
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)
20 views102 pages

Pamir Us First Semester 1

Uploaded by

saeedafghan01234
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/ 102

Programming in

C/C++
By: Ashiqullah “DANISH”
Pamir University First Semester
Introduction to programming
Introduction
You know that computer is one of the most advanced and fast growing technologies in the world. It is an electronic
device that receives, stores, retrieves and process information. Different computer languages are used for
communication between users and computers. It defines the rules under which programs are written to make use of
computers. Hundreds of computers languages are in use today, C is one of them, which is an excellent choice for
any data processing task.

Languages
Language is a source of communication among people/ among human beings.

What is the computer language?


To establish a communication between user and computer.
In general, there are two classes of languages
1. Natural languages
2. Programming Languages
Natural languages
These are the languages through which the human beings communicate with each other.
For example: English, Urdu, French, Pashto etc.

Programming languages
 These are the languages through which the human beings communicate with the computer.
 Programming language is a vocabulary and set of grammatical rules for instructing a computer to perform
specific tasks.
 For writing programs, programmers use special languages called programming languages.
Examples are C, C++, COBOL, PASCAL, BASIC, FORTRAN etc.

Programmers
Those who make/write programs are known as programmers or coders.

Levels of programming languages


The levels determine how near to the hardware. Programming languages are divided in two main categories.
1. Low level languages
2. High level languages
Low level languages
 These languages are close to the hardware (computer) and far from human being.
Computer can understand these languages easily. These languages understanding
are difficult for human beings.
Types of low level languages
1. Machine language
2. Assembly language
Machine language
 Machine Language was the first language used for computers as a source of communication. Machine
language is the only language that a microprocessor can understand directly and needs no translation
programs (compiler, Assembler, Interpreter).
 Machine language is also called the first-generation
programming language, or IGL.
 It is also called binary language or machine oriented language (MOL) or Machine
independent language (MIL). This language consists of two numbers, which are 0 and 1 (“0” means
“OFF” and “1” means “ON)
 "The set of binary codes which can be recognized by the computer is known as the Machine code "
 A program created in machine language cannot be run on any other computer

System expert
Those who know machine language is called system expert.
Assembly language
 It is also called Second Generation Language 2GL.
 The computer professionals developed one step higher language than the machine
language which is called Assembly language. The binary codes of machine language
(0’s and 1’s) were replaced by some special codes called mnemonics. These
mnemonics are understandable by the human but not understandable by the
machine. To make it understandable for the machine, a program called assembler is
developed its function is to translate a program written in assembly language into
machine language
 It is machine dependent. A program created on one computer cannot run on another
type of computer.
High level languages
 These languages are near to human and far from computers.
 We can learn and understand these languages very easily. Special
programs like compilers are used to convert these languages into
machine languages and enable the programmer to write instructions
easily using English words and familiar mathematical symbols such as
if else, for, goto, +, - etc.
Examples are BASIC, FORTAN, C, C++, COBOL, ADA, and PASCAL
The high level languages are of two types:
 Procedural languages/Structured languages.
 OOP (Object Oriented Programming) languages
Procedural language
A Procedural language is that in which each statement tells the computer to do
something. Get some input and process the input and provide the output to the user.

OOP
In this language different objects are created from each other and then used in
different functions.
Some common high level languages detail is given below
FORTRAN
FOR for formula
TRAN for translation
It is used to solve formula having problems i.e. Math's, Physics, Chemistry etc.
It is developed by John Backus and his team at IBM (International Business Machine).
It is a language that’s been around for nearly 40 years and is still used extensively for scientific and engineering
calculations, although C++ and other languages have eroded much of its usage.
COBOL
Common business oriented language.
It was released in 1960. The leader of the team that developed COBOL was will naval officers Grace Hopper. It
was used for solving business problems.
CPL
Combined programming language
It solves both formula+ business problem
BCPL
Basic Combined Programming Languages
BCPL was developed by Martin Richards at Cambridge University in 1967, for writing operating systems and
compilers.
It both solve formula problems (Math, Physics etc.) and as well as Business problem.
B-languages
It is designed by Kenneth Thompson. It is developed in AT and TS Bell LAB in
USA.
(AT and TS = American Telephone and Telegraphs). Therefore, it is called B-
Language. Bell starts from B. B programming language had advance features as
compared with BCPL. The UNIX operating system was first developed in B in
1970 at Bell Laboratory. Both BCPL and B were “type-less” languages. Thus each
data item in these languages occupied one “word” in the memory.
It is more advanced than other language like FORTRAN, COBOL) etc.
C-language
C is a programming language developed BY Dennis Ritchie at AT and T's Bell Laboratories of USA in 1972.
The C language was the advanced version of B language. It had many important concepts of BCPL and B. New
features, like data typing and many other functions were also included in C.
The next version of UNIX was revised and written in C. C language was developed as a computer independent
language. A program written in C can be run on any computer.

ADVANTAGES OF HIGH LEVEL LANGUAGES


 EASY TO LEARN, because the instructions written in English language
 MACHINE INDEPENDENT, because a program written in High level language can be used on any computer
system for which the compiler of the language is available.
 Less time needed for writing programs
 Many programmers are available.
 C code is portable, portable means that it is easy to adapt software written for one type of computer or
operating system to another. For example, if you can easily convert a program written for UNIX so that it runs
under windows, that program is portable.
Language Translators / processors
•Translators are programs, which translate programs written in any high or assembly language into
machine language (1’s and 0’s).
•Language processors are the computer programs which converts a source program into object program.

There are three types of language translators


Assembler
Compiler
Interpreter
Assembler
•The software that translates and assembly code into the computer’s machine code is called assembler.
•A program written by a programmer in assembly language is called source program.
After this source code has been converted into object code
Compiler
A compiler is a computer software that translates a whole program, called the
source code at once into machine code (object code)
Interpreter
An interpreter in another type of translator used for translating a language
program into machine code. It takes one statement of program and translates it
into a machine instruction which is immediately executed by computer. If there
is any error in the instruction, it indicates the error and program execution stops.
Program
Program is a set of instructions, or a set of sequential instructions which are given to computer
to solve a specific problem/ to perform a specific task. Programs are written in computer
languages like BASIC, PASCAL, C etc.
Different types of Programs
Generally, there are THREE types of Programs that’s are created in a programming Languages.
1. Source Programs
2. Object Programs
3. Executable Programs

Source code
A computer program written in a high level language is called the source code or
source program. It is a human understandable form not computer understandable
form.
Source files, which have the filename extension.cpp/C, contain function definitions.
Any definitions for data type you have created yourself that are required for the code
in a .cpp/C file are added by including the contents of one or more .h files at the
beginning of the.cpp file.
Object code
 A program that is created by the language processor in the form of codes is called Object program.
 A program that is converted in to object language (Machine) is called object program.
 A computer program in the machine language is called the object code or object program. A
program written in machine language runs directly on the computer and no need for translator
(compiler, interpreter).

Executable Program/code
 A program that is created by language processor to show or provide the output of a
source program.
 A program that is directly run or executes to provide results of the input.
 When source and object program are linked that’s create a new executable program
is called exe program.
Brief history of C++ Language
History of C++
In early 1980, C++ was developed by Bjarne Stroustrup. It was an extension of C. it was designed for
the UNIX system environment. C++ enabled programmers to improve the quality of code. It included
object oriented programming.

Why name of C++ is Plus Plus ?


 C++ development began in 1979, four years before its release, and it did not start with the name
C++, its first name was C with Classes.
 In the late part of 1983, C with classes was first used for AT and T’s internal programming needs.

Its name was changed to C++ later in the same year. The C++ name was suggested by Rick

Mascitti. It was used in December of 1983 when it was edited into the final copies of
[Stroustrup 1984] and [Stroustrup 1984c]. C++ is pronounced C plus plus.
 The language is not called D, because it is an extension of C. it is not arranged alphabetically, as C-
Language after B-language
 ++ is the increment operator of C, it means added a new feature to C called classes, therefore, given a
name C++. (i.e. C + Classes means classes=+ (C++)), this ‘C+’ is wrong syntax. C++ is correct.
 C++ was not commercially until the late part of 1985.
 C++ implements data abstraction using a concept of called classes, along with other features to allow
object-oriented programming and is considered a High level Language.
 Classes help programmers with the organization of their code. They can also be beneficial in assisting
programmers to avoid mistakes.
 The original C++ compiler, called Cfront, was written in the C++ programming language.
History
• C is a programming Language which is developed during 1970 by Dennis Ritchie . In
the case of this language the data was not secured.
• C Language is not an object oriented language it is a procedural oriented language.
Now what is Object Oriented Language it will be discuss later.
• In C programming, a program can be divided into smaller programs called functions.
And it doesn't support Function overloading.
• C++ is also called as C with classes or we can say C++ is a C language with more
features.
History
•C++ is a High-level programming language developed by
BJARNE STROUSTRUP starting in 1979 at Bell Labs.
originally named C with Classes but later it was renamed C++
in 1983.
C++ runs on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX

Creator of C++ Language


Use of C++

• C++ is being highly used to create computer programs like device


drivers Anything from art applications, music players and even video
games. And etc.
• Keep in mind….just like you wouldn't be able to write a book in
Spanish after taking a few classes, same you won't be making any
serious video games.
• Programming, like many skills, takes time. This is something many
people sadly learn every day.
Compiler and IDE for C++

What is compiler?
• Computers understand only one language and that language consists
of sets of instructions made of ones and zeros. This computer
language is appropriately called machine language.
• A single instruction to a computer could look like this: 00011101010101

If we want to give instruction to the computer for example 2+2=4 so compiler


convert our instruction to something shown bellow.
0010 + 0010 = 0100
What is IDE ?

• IDEs are some tools which are use to write code for C++ for
example
DEV C++, Turbo C++, Visual Studio, Eclipse and
etc.
• The Dev C++ is much famous for learning C++ that is why we
use the Dev-C++ IDE (Integrated Development Environment)
• Dev-C++ has its own compiler which is responsible for the
conversion of your code into machine language.
First Program In C++

This is a preprocessor directive. It tells the


preprocessor to include the contents of
iostream header file in the program before
compilation. This file is required for input
output statements.

This will be discuss later. For now it is


required to write it

The main function is responsible to begin the


program, it mean the program start from here, it
include body of your program.
Comments in C++

• Each and every language will provide this great feature which is used to
document source code. We can create more readable and eye catching
program structure using comments. We should use as many as comments
in C++ program. Comment is non executable Statement in the C++.
• We can have two types of comment in Programming
Single Line Comment
Multiple Line Comment
#include<iostream>
using namespace std;
//Ashiqullah Danish Computer Programmer
main(){

Comments /* hey, in this semester you will learn C++ Programming


Example basics, Oops and many more
*/
cout<<“ this is the First Program in C++”;

}
C++ supports the following data types:

• Primary or Built-in or Fundamental data type


• Derived data types
• User-defined data types
Primitive Data Types

• 1. Primitive Data Types : These data types are built-in or predefined data
types and can be used directly by the user to declare variables. example: int, char,
float, bool, etc. Primitive data types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character
Derived Data Types

• Derived data types: that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointer
 Reference
Abstract or User-Defined Data Types
• Abstract or User-Defined Data Types: are defined by the user itself. Like, defining a class
in C++ or .a structure. C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
Data Types & Variables
• While doing programming, you need to use variables to store information.
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
• You may like to store information of various data types like character,
wide character, integer, floating point, double floating point, Boolean
etc. Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Data Types & Variables
• Data Types means characteristic of a data. Bellow are some of the data types
in C++,
Type Keyword Size reservation
Boolean Bool 1 byte
Character char 1 byte
Short integer short int 2 bytes
Integer int 4 bytes
Floating point float 4 byte s
Double floating point double 8 byte s
Variable and Assignment
Assignment is a process through which we store some values to a variables. Assigning
value to a variable need two process
1. Variable Declaration
2. Variable initialization
What is variable Declaration?
Variable Declaration tell the system you have allocate a space by a specific name.
To declare a variable you need two things. Data Type and variable name (identifier).
For example int var1; char var2; double x; string y;
Variable and Assignment
What is variable initialization?
Variable initialization means assigning values to variable, it is the way how you
can insert values to the variable. For example
int x; //variable declaration
x=90; // variable initialization
Or
int x=80; //variable declaration + variable initialization
Examples
We can declare and initialize a variable through different ways

One Variable You can declare


and initialize
multiple variable
You can declare in in same line.
same line multiple
More than one Variable variables
Keywords

• Keywords are some reserve words in C++ programming which are


already taken by the certain language and you can not assign the reserved
word to any variable, function, class and etc.
• Exapmle:
• Int, cin, cout, iostream, double, string, include and etc.
But you can assign the name of variable as
Abc, khan, sname, password, username and etc
Constant

Constant are like variable, but once you assign a value to a constant variable it is not
changeable. Where the variables are changing their values during the execution of a
program.
Example
const int x=90;
x=80; // this is an error
cout<< x;
Character

Character is a single alphabet which takes only one byte in computer memory and it
is always define as bellow.
Syntax char variable_name;
Example char x;
x=‘Z’;
cout<<x;
Strings
String is the collection of characters, it is also called non-primitive data type
and it assume storage size depends on the character of string.
Syntax string variable_name;
Example string student_name;
student_name=“Kamal”;
cout<<student_name;
cin/cout
cin and cout are not keywords, as you are beginner
now in this class just consider them as a keyword.
cout means console out. It is use to print something
on the screen of your system. We use the extraction
operator(<<) with cout. Reverse cin is use for input
when you want to take something from the user
through keyboard. We use the insertion operator
(>>) with cin .
Example
Operator
Operator is a special symbol that tells the compiler to perform specific
mathematical or logical Operation.

These are the overall C++


Operators, we are going to
discuss all of them one by
one with the practical
examples.
For now in this class we
covers the Arithmetic,
Unary and Relational
Operators. The others will
be debussed later
Arithmetic operator program

To understand the arithmetical


operators look at this program.
Increment & Decrement
Operators

The increment operator (++) adds 1 to its operand, and the decrement
operator (--)subtracts 1 from its operand.
x = x+1; is the same as x++
x = x-1; is the same as x--

Both the increment and decrement operators can either Prefix or Postfix.
There is an important difference in prefix and postfix forms which will be
discuss later

++x // Prefix increment form x++ // Postfix increment form


Data Flow Statements
Decision Making
• Conditional statements
• The statement of a computer program is executed one after the other in the
order in which they are written. This is known as sequential execution of the
program.

• The order of execution of the statements in a program can be changed. This
done with the help of conditional statements. The condition statements are used
to execute a set of statements after testing a condition. The conditional
statements are also called selection statements.
Relational expression
• A relational expression consists of constants, variables and arithmetic expressions
that are combined by a relational operator.
• Example
• 10>6 is a relational expression.

• Relational operators
• A relational operator is a symbol that is used to find a relationship between two expressions.
• Following is a list of relational operators available in C++.
• Greater than >
• Greater than or equal to >=
• Less than <
• Less than or equal to <=
• Equal to ==
• Not equal to. !=
The "If" statement
• The "if" statement is used to execute or ignore a set of statements
after testing a condition.
• #include<iostream.>
• Using namespace std;
• main()
• {
• int marks;
• cout<<"Enter marks: ";
• cin>>marks;
• if (marks<33)
• {
• cout<<"fail"<<endl;
• }
• cout<<"Marks obtained: "<<marks;
• }

Examples of If
• #include<iostream>
• Using namespace std;
• main()
• {
• int a ,b;
• a=10;
• b=80;
• if(a>b)
• {
• cout<<"a is greater than b";
• }
• cout<<"ok";
• }
• #include<iostream>
• Using namespace std;
• main()
• {
• int n;
• cout<<"enter a value for n: ";
• cin>>n;
• if(n>10)
• {
• cout<<"Afghanistan";
• }
• cout<<"\n ok";
• }
• #include<iostream>
• using namespace std;
• main()
• {
• int n;
• cout<<"enter a number?";
• cin>>n;
• {
• if(n%3==0)
• cout<<"number is divisible by 3"<<endl ;
• }
• cout<<"ok";
• }
If else Example
• Write a program to input a number from the keyboard and then print the message "it is an odd
number" if it is an odd number. Else print message "it is an Event number".
• #include<iostream>
• using namespace std;
• main()
• {
• int n;
• cout<<"Enter a Number in N ? :";
• cin>>n;
• if(n%2==1)
• cout<<"it is an odd number ";
• else
• cout<<"it is an even number ";
• }
• Write a program to input two integers and then to find out whether these numbers are equal or different
• #include<iostream>
• using namespace std;
• main()
• {
• int a,b;
• cout<<"Enter first value? ";
• cin>>a;
• cout<<"Enter second value? ";
• cin>>b;
• if (a==b)
• cout<<"Both values are equal ";
• else
• cout<<"Both values are different ";
• }
• write a program to find a vowel if entered value is vowel, print message
• consonant if entered value is consonant.
• char alphabet;
• cout<<"Enter a character: ";
• cin>>alphabet;
• if(alphabet=='a')
• cout<<"vowel";
• else if(alphabet=='A')
• cout<<"vowel";
• else if(alphabet=='e')
• cout<<"vowel";
• else if(alphabet=='E')
• cout<<"vowel";
• else if(alphabet=='i')
• cout<<"vowel";
• else if(alphabet=='I')
• cout<<"vowel";
if, if...else & nested if

The if, if...else and nested if...else statement are used to make one-time
decisions in C++ Programming, use to execute some codes and ignore some
codes depending upon the test condition.
if Statement
The if statement checks
whether the test condition is
true or not. If the test
condition is true, it executes
the code/s inside the body of
The if keyword is followed by test condition inside
if statement. But if the test parenthesis ( ). If the test condition is true, the codes
condition is false, it skips the inside curly bracket is executed but if test condition is
false, the codes inside curly bracket { } is skipped and
code/s inside the body of if control of program goes just below the body of if as
statement. shown in figure above
Flow Chart of if Statement
Else if Statement
This statement is executed when if
statements become fail. So the compiler
checks for the else if statement. Same if the
first else if statement become fail again it
will check for the third else if statement,
same action will be perform. If none of the
if and else if statement become true then the
last bock (else block) will be execute.
Else if flow Chart
Nested if Statement
When ever an if statement comes
inside of an if statement, it is
called Nested if statement. It
means this has two test condition
for execution of a program.
See the example
Nested if Flow Chart
C++ Switch Statements
• Use the switch statement to select one of many code blocks to be executed.
• Syntax
• switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Switch
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each case.
Switch Rules
• The expression used in a switch statement must have an integral or
enumerated type.
• You can have any number of case statements within a switch. Each case
is followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
Switch Rules
• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
Example

More example will be discussed


#include<iostream>
Using namespace std;
main()
{
char Gender;
cout<<"Enter Gender: m for Male and f for female:.......";
cin>>Gender;
switch (Gender)
{
case 'm':
cout<<"I am Male ";
break; // if here not write a break then the case ‘f’ statement will also execute

case 'f':
cout<<"I am Female ";
break; //if here not write a break then the default statement also execute

default:
cout<<"You have selected a wrong choice";

}
cout<<"thank you";
}
• This is how it works:
• The switch expression is evaluated once
• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break and default keywords are optional, and will be described
later in this chapter
• The example below uses the weekday number to calculate the
weekday name:
• Example
• int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
Loops
• When you need to execute a block of code several Body of loop
number of times we use some statements which are
called loops statement. In fact loop statement
allows you to execute a statement or a group of
statement multiple time. True
Condition
• following is the general form of a loop statement in
most of the programming language. False

Exit from loop


Loops
A statement or a set of statements that is executed
repeatedly is called a loop. The statements in a loop are
executed for a specified number of times or until some
given condition remains true.
In C++, there are four kinds of loop statements. These
are
Types of Loop
C++ provide the following types of Loop statement.
1. While loop
2. For loop
3. Do while loop
4. Nested loop
Flow Chart

While loop
• A while loop statement repeatedly
executes a target statement as long
as a given condition is true
• Syntax:

While (condition ){
Statements
}
Program

main(){
int a=0;
while(a<10){
Cout<<“Welcome to Pamir University”;
a++;
}
Flow Chart
For Loop
• A for loop is a repetition control structure
that allows you to efficiently write a loop
that needs to execute a specific number of
time.
• Syntax:
for(initialization ; condition ; increment){
Statements;
}
Program

main(){
int i;
for(i=0; i<10; i++){
cout<<“ Welcome to First Semester”;
}
Do… While loop Flow Chart

As we studied while and for loops, they were


checking for condition first and then execute
the statement. But do…while loop execute the
statement and then it check the condition for
further execution.
Syntax:
do{
Statements;
}while (condition)
Program
Arrays
• An array is a list of elements of the same data type, identified by a pair of square
brackets [ ]. To use an array, you need to declare the array with 3 things:
1. Array Type
2. Array name
3. Array Size
Instead of declaring individual variables, such as num0, num1, ..., and num99, you
declare one array variable such as numbers and use num[0], num[1], and ... num[99] to
represent individual variables. A specific element in an array is accessed by an index
Array Declaration
To declare an array in C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows:
Type arrayName[arraylength]; This is called a single-dimension
array. The arraySize must be an
integer constant greater than zero
and type can be any valid C++
data type. For example, to declare
a 10-element array we use the this
int num[10]; statement.
Initializing Arrays:
Array elements can be initialize one by one or using a single statement as follows:
Direct Initialization
int number[5]={20,30,40,50,70};
Initialization by Index
num[0]=20; Printing array
Cout<<num[0]<<endl;
num[1]=30; Cout<<num[1]<<endl;
num[2]=40; Cout<<num[2]<<endl;
Cout<<num[3]<<endl;
num[3]=50; Cout<<num[4]<<endl;
num[4]=60;
num[5]=70
Initializing Arrays
An element is accessed by index number of an array. This is done by placing
the index of the element within square brackets after the name of the array.
For example: int num[9];
The above statement will take 9 elements. So here is an example that cover the
declaration, and initialization of the array by index number.
Num[0] Num[1] Num[2] Num[3] Num[4] Num[5] Num[6] Num[7] Num[8]
num 10 20 30 40 50 60 70 18 90
Initialization with loops
int num[9];
Output

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


Or
1
cin>>num[i]=i; 2
} 3
4
for(int i=0;i<10;i++){ 5
6
7
cout<<num[i]<<endl; 8
} 9
Multi-Dimensional Array
int num[2][4];

It is in the form of table which


is the collection of row and columns
It is also called 2D array
Initialization of 2D arrays
Direct Initialization
int num[3][3]={{2,3,4},{8,9,7},{22,33,44}};
Or
Through index number
Printing 2D array
Num[0][0]=90 Cout<<num[0][0]<<endl;
Num[]0[1]=90 Cout<<num[0] [1]<<endl;
Num[0][2]=90 Cout<<num[0] [2]<<endl;
Num[]1[0]=90 Cout<<num[1] [0]<<endl;
Cout<<num[1] [1]<<endl;
Num[1][1]=90
Num[1][2]=90
Initializing 2D array with loops
Initializing values Printing values
for(r=0;r<3;r++){ for(r=0;r<3;r++){
for(c=0;c<3;c++){ for(c=0;c<3;c++){
cin>>sal[r][c]; cout>>sal[r][c];
} }
} }
Methods/Functions
Sometime a portion of code has to use many times. Instead of re-writing the
codes many times, it is better to put them into a "subroutine", and "call" them
many times.
The benefits of using functions are:
Avoid repeating codes: It is easy to copy and paste.
Software Re-use: you can reuse the functions in other programs, by packaging
them into library codes.
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Create a Function

A function is a group of statements that together perform a task. Every C++


program has at least one function, which is main(), and all the most programs
can define additional functions, so each function performs a specific task.
There are two types of functions
1. User define Function
2. Built-in function or Standard library function
User Define Functions
A function which is declare by the user according to his\her requirements is called
user define functions

Every User define function has three parts


A function declaration tells the
1. Declaration of a function compiler about a function's name,
return type, and parameters
2. Definition of a function
3. Calling of a function
A function definition provides the
actual body of the function.
A function calling is use to call the
function or we can say a function
calling is use to tell the function to
preform its task.
Example
#....
Using namespace std;
void print(); // function declaration

main(){

print(); // function calling


} This is a user define function with no return type and no
parameter.
Void print(){ // function definition
int number=100;
Cout<<“welcome to functions class..!!<< number;
}
Syntax of a user define function
return_type function_name( parameter_list){
Body of a function Return Type: A function may return a value. The return_type is the
data type of the value the function returns. Some function may not
Return value; return if you use the void keyword
} Function Name: This is the actual name of the function.
Parameters: function take argument values. And further perform a
task on values.
Function Body: The function body contains a collection of
statements that define what the function does.
Function Overloading
• When we have same name functions with
different set of
arguments(type,order,number) is called
Function Overloading.
Pointers
• Pointers are the powerful feature of C++ programming which differs it from
other popular programming languages like: Java, Visual Basic etc.
• To understand pointers, you should have the knowledge of address in
computer memory.
• Computer memory is broken down into bytes and each byte has its own
address. For example: In 1KB memory, there are 1024 bytes and each byte is
given an address (0 - 1023).
Example
• The & operator can find
address occupied by a variable.
If a, b are variables then, &a
and &b gives the address of
those variables.
Pointer Variable
• Consider a normal variable as int a=60, these variables holds data. But pointer
variables are the special types of variable that holds memory address instead of
data. To declare pointer variable use : int *p; OR int* p;
// example
int a=10;
int *ptr;
ptr=&a;
cout<<ptr;
Pointer to an array
Pointers are the variables that To access the address of the all
elements in array we use the for loop
hold address. Pointers can
point at cells of an array not int arr[5];
only single variable int *ptr;
For(int i=0;i<=5;i++){
int a[5];
ptr= &arr[i];
int* ptr; cout<<ptr<<endl;
ptr = &a[2]; }
Structures in C++
• Structure is the collection of variables of different data types under a single
name for better visualization of problem. Arrays is also collection of data
but arrays can hold data of only one type whereas structure can hold data of
one or more types.
• The struct keyword defines a structure type followed by an identifier(name
of the structure). Then inside the curly braces, you can declare one or more
members (declare variables inside curly braces) of that structure.
Example

Structures are declare out of the main function


and then called inside the main function,

You might also like