Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
62 views

21CSS101J - Programming For Problem Solving Unit II

The document discusses control statements in C programming. It covers various conditional statements like if, if-else, nested if-else, else-if ladder, switch case statements. It provides examples to check conditions like whether a number is odd, even, positive, negative etc. It also demonstrates nested if-else to validate login credentials and use of else-if ladder. The document explains rules for switch case statement and provides a program example to perform arithmetic operations using switch case.

Uploaded by

Dhruv Juneja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

21CSS101J - Programming For Problem Solving Unit II

The document discusses control statements in C programming. It covers various conditional statements like if, if-else, nested if-else, else-if ladder, switch case statements. It provides examples to check conditions like whether a number is odd, even, positive, negative etc. It also demonstrates nested if-else to validate login credentials and use of else-if ladder. The document explains rules for switch case statement and provides a program example to perform arithmetic operations using switch case.

Uploaded by

Dhruv Juneja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

SR

INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.
21CSS101J – Programming for Problem
Solving Unit II
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

UNIT II
Conditional Control -Statements :Simple if, if...else -
Conditional Statements : else if and nested if - Conditional
Statements : Switch case - Un-conditional Control Statements :
break, continue, goto - Looping Control Statements:for, while,
do..while - Looping Control Statements: nested for, nested
while - Introduction to Arrays -One Dimensional (1D) Array
Declaration and initialization - Accessing, Indexing and
operations with 1D Arrays
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

UNIT II
Array Programs – 1D - Initializing and Accessing 2D Array,
Array Programs – 2D - Pointer and address-of operators
-Pointer Declaration and dereferencing, Void Pointers, Null
pointers, Pointer based Array manipulation
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements
❑ Also called as Conditional Statement
❑ Decides order of execution based on conditions
❑ Helps repeat a group of statements
❑ Modifies control flow of program
❑ Decision Making
❑ Branching
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Types of Branching Statements
a) if statement
i. Simple if
ii. if…else statement
iii. nested if…else statement
iv. else…if statement
b) switch statement
c) goto statement
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


a) if statement
❑ Condition “True" - Statement block will be executed
❑ Condition “False“ - Statement block will not be
executed.
❑ Variations
i. Simple if
ii. if…else statement
iii. nested if…else statement
iv. else…if statement
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


i. Simple if statement
❑ Basic if statement
❑ What is a condition?
❑ Executes statement block only if condition is true
❑ Syntax if (condition)
{
Statements;
}
/* Simple if – Program to check whether a number is
Odd*/ #include<stdio.h>
int main( )
{
int number;
printf(“Enter the Number:
”); scanf(“%d, &number);
if(number%2==0)
{
printf(“The Number is Even”);
}
return 0;
}
Output
Enter a value :
10342 The
number is Even
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Try it Out Yourself ! Write a C program
to:

1) Check whether the given number is Odd

2) To check whether the given number is Greater

3) To check whether the given number is Smaller

4) To check whether the given number is positive

5) To check whether the given number is negative

6) To check whether the given number is zero


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


ii. If else statement
❑ Extension of basic if statement
❑ Takes care of True and False condition
❑ Number of Statement Blocks - 2
❑ Block 1 – True Condition
❑ Block 2 – False Condition
if (condition)
{
Statements;
}
Else
{
Statements;
}
/* if else –To check whether a number is Odd or
Even*/

#include<stdio.h>
int main( )
{
int number;
printf(“Enter the Number: ”);
scanf(“%d, &number);
if(number%2==0)
{
printf(“The Number is Even”);
}
else
{
printf(“The Number is Odd”);
}
return 0;
Output 1
Enter the Number : 10341
The number is Odd

Output 2
Enter the Number : 10342
The number is Even
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Try it Out Yourself ! Write a C program to:

1) To check whether the given number is Greater or


Smaller

2) To check whether the given number is +ve or -ve

3) To check whether two numbers are equal or not


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


iii. Nested if else statement
❑ Used when a series of decisions
are involved
❑ Makes a choice between
several alternatives
❑ New if else statement block is
used within existing if else
statement block
/*Program for Nested if else */

#include <stdio.h>

void main( )

char username;
int password;

printf("Username:");

scanf("%c",&username);

printf("Password:");

scanf("%d",&password)
if(username=='a')
{
if(password==12345)
{
printf("Login successful");
}
else
{
printf("Password is incorrect, Try
again.");
}
}
else
{
printf("Username is incorrect, Try again.");
}
return 0;
}
Output 1
Username: a
Password:
12345 Login
Successful

Output 2
Username: a
Password:
54321

Password is incorrect, Try again.

Output 3
Username: b
Password:
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Step 1: First if condition will be true, if the user has typed 'a' as a
username then the program control moves to second if condition
and checks for the password

❑ if it true it will print 'login successful’


❑ else it will execute block statement 'Password is Incorrect,
Try again.‘.
❑ Step 2: If the first if condition is false then it executes last else
block thus printing 'Username is Incorrect, Try again.‘
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Step 3: In this above example we have use username as single
character to use multiple character username we need to use
string data type
else if Ladder
/*Program for if else ladder*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


b) Switch statement
❑ Allows to make decisions from a number of choices
❑ Also called as Switch-Case-Default Statement
❑ Faster than nested if else statement
❑ Easier to understand
❑ Rules for writing switch ( ) statement
❑ Expression in switch must be an integer value or
a character constant

❑ No real numbers used in Expression


SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Each case block anddefault block must endwith
break
statements
❑ Default is optional
❑ Case keyword must end with colon ( : )
❑ Default may be placed anywhere in the switch
❑ No two case constants are identical
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...

switch(variable or expression)
{
case constant 1:
statements;
break;
….
case constant N;
statements;
break;
default:
statements;
}
/* Program for Switch
Case*/

#include<stdio.h>
int main( )
{
int a, b, choice;
printf(“\nEnter Two Numbers:
”); scanf(“%d%d”, &a,&b);
printf(“\n Enter 1 for Addition”);
printf(“\n Enter 2 for
Subtraction”);

printf(“\n Enter 3 for Multiplication”);


printf(“\n Enter 4 for
switch (choice)
{
case 1:
printf(“Sum is : %d”,
a+b); break;
case 2:
printf(“Difference is : %d”,
a-b); break;
case 3:
printf(“Multiplication is : %d”,
a*b); break;
case 4:
printf(“Difference is : %d”,
a/b); break;
default:
printf(“Invalid Choice:”);
}
getch( );
}

Enter two numbers


20
10
Enter 1 for Addition
Enter 2 for Subtraction
Enter 3 for Multiplication
Enter 4 for Division
Enter your Choice: 3
Product is : 200
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


❑ Nested Switch statement
❑ Inner switch( ) can be a part of an outer switch( )
❑ Inner switch( ) and outer switch( ) case constants may be the

same
/* Program for Nested Switch
Case*/

#include<stdio.h>
int main( )

{
int square, i, n, fact = 1,choice;
printf(“\n Enter Any Number: ”);
scanf(“%d”, &n);
printf(“ 1. Square \n”);
printf(“ 2. Factorial
\n”);

printf(“ 3. Find Odd or Even \n”);


printf(“ 4. Exit \n”);
printf(“ Enter your Choice”);
switch (choice)
{
case 1:
square = n * n;
printf(“TheSquare of the Given number is
%d\n”,
square);
break;
case 2:
for(i=1;i<=n;i++)
{
fact = fact * i;
}
printf(“The Factorial of a given number is %d\n”, fact);
break;
switch (n%2)
{
case 0:
printf(“Given Number is
Even\n”); case 1:
printf(“Given Number is Odd\n”);
}
case 3:
exit(0);
default:
printf(“Invalid Choice. Please try
again\n”);
}
return 0;
}
Enter any number
5
1. Square
2. Factorial
3. Find Odd or Even
4. Exit
Enter your choice
2
The factorial of a given number is: 120
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 1 Control Statements Contd...


c) The goto statement
❑ Transfers control from one point to another
❑ Syntax
goto label;
statements;
……………
label
statements;
SR
MOF SCIENCE AND
INSTITUTE
TECHNOLOGY,
CHENNAI.
2.1 break

The break statement ends the loop


immediately when it is encountered.

Its syntax is: break;

The break statement is almost always


used with if...else statement inside the
loop.
SR
MOF SCIENCE AND
INSTITUTE
TECHNOLOGY,
CHENNAI.
2.1 Continue
The continue statement skips the
current iteration of the loop and
continues with the next iteration.

Its syntax is: continue;

The continue statement is almost


always used with the if...else
statement.
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements
❑ Loop – A segment of the program that is executed repeatedly
until a condition is satisfied
❑ Classification – Entry Controlled & Exit Controlled
❑ Types
a) while do loop
b) do while loop
c) for loop
i. Nested for loop
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


a) The While Loop
❑ Simplest looping structure in C
❑ Statementsin the program may need to repeat for

many times. e.g., calculate the value of n!

❑ Loop consists of two segments


❑ Control Statement
❑ Body of the Loop
❑ How while loop works?
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

Initialize loop counter variable;


while (condition)
{
Statements;
increment / Decrement loop
counter variable;
}
/* Program to Add 3
Numbers*/

#include<stdio.h>
int main( )
{
int a, b, c, sum;
printf(“\n Enter the Three Numbers: ”);
scanf(“%d%d%d”, &a,&b,&c);
sum = a+b+c;
printf(“The sum of 3 Numbers is %d”,
sum); return 0;
}
Output
Enter the Three Numbers: 10 20 30

The sum of 3 Numbers is: 60


/* Program to Add n Numbers*/

#include<stdio.h>
int main( )
{
int i=1,n, sum=0;
printf(“\n Enter the value for n: ”);
scanf(“%d”, &n);
while (i<=n)
{
sum = sum + i;
i++;
}
printf(“The sum of n Numbers is: %d”,
sum); return 0;
}
Output
Enter the value for n: 5
The sum of n Numbers is: 15
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ Try it Out Yourself ! Write a C program to:

1) To print all even numbers from 1 to 100

2) To print all even numbers from 1 to n

3) To print table for any number

4) To calculate the sum of its digits

5) To check whether the entered number is Prime or not

6) To get a number as input and print it in reverse.


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


b) The Do While Loop
❑ The body of the loop is executed at least once
❑ Syntax
do
{
statements;
}
while (condition);
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.
Initialize loop counter

variable; do

{
Statements;
increment / Decrement loop
counter variable;
}
while (condition)
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


While Do Loop Do While Loop
Entry Controlled Loop Exit Controlled Loop

Test condition is checked Test condition is checked after the


before body of the loop is executed body of the loop is executed
Loop will not be executed if Loop will be executed at least once
condition is false even if condition is false
Top tested loop Bottom tested loop
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


c) The for loop
❑ Most commonly and popularly used loop structure
❑ Structure of the for loop
❑ Initialize loop counter variable
❑ Check for condition
❑ Increment / Decrement the loop counter variable
❑ Syntax
for(initialization; condition; increment / decrement)
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ Examples
i. for(i = 0; i < n; i++)
{
Statements;
}
ii. for(count = 0; count > n; count--)
{
Statements;
}
/* Program to Add n Numbers using for loop
*/

#include<stdio.h>
int main( )
{
int i, n, sum=0;
printf(“\n Enter the value for n: ”);
scanf(“%d”, &n);
for (i =1; i<=n; i++)
{
sum = sum + i;
}
printf(“The sum of n Numbers is: %d”, sum);
return 0;
}
Output
Enter the value for n: 5
The sum of n Numbers is: 15
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for syntax
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for Example Program
#include<stdio.h>
#include<conio.h>
main()
{
Int row, column;
for(row=1;row<=5;row++)
{
for(column=1;column<=row;column++)
{
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for Example Program
print(“*”);
}
print(“\n”);
}
getch();
Output:
*
**
***
****
*****
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for Example Program
#include<stdio.h>
#include<conio.h>
main()
{
Int ro,sp,st,no;
printf(“Enter no. of rows you want to print\n”);
scanf(“%d”, &no);
for(ro=1;ro<=no;ro++)
{
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for Example Program
for(sp=no-ro;sp>=1;sp--)
printf(“ “);
for(st=1;st<=2*ro-1;st++)
printf(“*”);
printf(“\n”);
}
for(ro=no-1;ro>=1;ro--)
{
for(sp=1;sp<=no-ro;sp++)
printf(“ “ );
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested for Example Program
for(st=1;st<=2*ro-1;st++)
printf(“\n”);
}
getch();
}
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


Output
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ nested while loop
• Using while loop within while loop is said to be nested while
loop.
• It is used to execute a set of code for multiple times as long as
the condition is true.
• Once the condition becomes false the code block is no longer
executed.
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ Syntax
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


#include<stdio.h>
int main()
{
int row, j;
for(row=’A’;row<=’D’;row++)
{
for(j=’A’;j<=row;j++)
{
printf(“%c”, j);
}
printf(“\n);
}
return 0;

}
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ Output

A
AB
ABC
ABCD
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


#include<stdio.h>
int main()
{
int row, j;
for(row=1;row<=5;row++)
{
for(j=1;j<=5;j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
return 0;
}
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


Output:

12345
12345
12345
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 2 Looping Statements Contd...


❑ Try it Out Yourself ! Write a C program to:

1) To print all even numbers from 1 to 100

2) To print all even numbers from 1 to n

3) To print table for any number

4) To calculate the sum of its digits

5) To check whether the entered number is Prime or not

6) To get a number as input and print it in reverse.


SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 3 Arrays
❑ Definition
An array is definedas finite ordered collection of
homogenous data, stored in contiguous memory locations.

✔ Array is used to store a collection of data


✔ Array is a collection of variables of the same type.
First Last
Element Element

Numbers[0] Numbers[1] ……. Numbers[n]


SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Need for Arrays
❑ Used to represent a list of numbers / names
❑ Used to represent tabular data in 2, 3 or more dimensions
❑ Important Data Structure in any programming language
❑ Definition
❑ Collection of elements of similar data types
❑ Each element is located in separate memory locations
❑ Each Array element share a common name
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Characteristics of Arrays
❑ All elements in the arrays share a common name
❑ Elements distinguished by index number
❑Index (or) element number of an array plays vital role for calling
each element

❑ Specific array elements can be modified


❑ Value of array element can be assigned to variables
❑ Array elements stored in continuous memory locations
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Storage space for array depends on its data type and size
Total bytes = sizeof (Data type) x Size of Array
❑ Example
int a [5];
Total bytes = sizeof (int) x 5 = 2 x 5 = 10 bytes
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
a) Array Declaration
❑ Syntax
Datatype arrayname [size/subscript];
❑ Data Type: int, float, double, char, structure, union
❑ Array Name: Name given to the Array variable
❑ Size / Subscript: Number of values an Array can hold
❑ Examples int numbers[5]; float marks[50];
char name[20]; double a[i];
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Illustration

int a[n];
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Static Array: Array size (range) declared in the program
❑ Dynamic Array: Array size given during execution

STATIC ARRAYS DYNAMIC ARRAYS

Range / Size of an array included Range / Size of an array


in the Array definition not included in the Array
definition
Static Arrays cannot be changed Dynamic Arrays can be changed
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
b) Array Initialization
❑ Initialization: Assigning values to array elements
❑ Values specified in curly braces separated by
commas
❑ Examples
int a[ 5] = {1, 2, 3, 4, 5};
float b[3] = { 40.5, 59.0, 98.5};
char name[6] = ” SRMIST”;
❑ Array element index start from 0
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Array elements are called by array names followed by the
element numbers
❑ int a[ 5] = {1, 2, 3, 4, 5};
a[0] refers to 1st element i.e., 1
a[1] refers to 2nd element i.e., 2
a[2] refers to 3rd element i.e., 3
a[3] refers to 4th element i.e., 4
a[4] refers to 5th element i.e., 5
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
c) Getting Input for Arrays
❑ Use for loops to get input in arrays
❑ Use for loops with regard to the Array’s dimension
❑ Input for One Dimensional Arrays – 1 for
loop for(i = 0; i < 5; i++)

{
scanf(“%d”, &a[i]);
}
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Input for Two Dimensional Arrays – 2 for loops
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
d) Printing Output in Arrays
❑ Use for loops to print array output
❑ Use for loops with regard to the Array’s dimension
❑ Printing One Dimensional Array Output – 1 for
loop for(i=0;i<5;i++)

{
printf(“%d”,a[i]);
}
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
❑ Printing Two Dimensional Array Output – 2 for loops
for(i = 0; i < 5; i++)
{
for(j=0; j < 5; j++)
{
printff(“%d”, a[i][j]);
}
}
/* Program 1 : Array Declaration & Initialization*/

#include<stdio.h>
int main( )
{
int i, arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for(i=0; i<=n;
i++)
{
printf(“%d”\n, a[i]);
}
Output
10
20
30
40
50
/* Program 2 : Array Declaration & Initialization*/

#include<stdio.h>
int main( )
{
int i, arr[5];
arr[5] = {10, 20, 30, 40, 50};
for(i=0; i<=n; i++)
{
printf(“%d”, a[i]);
}
return 0;
}
Output
10
20
30
40
50
/* Program 3 : Array Declaration & Initialization*/

#include<stdio.h>
int main( )

{
int i, n, arr[5];
scanf(“%d”, &n);
printf(“Enter the Elements of Array\n”);
for(i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
}
printf(“The Elements of the Array are”\n”);
for(i=0; i<n; i++)
{
printf(“%d”, a[i]);
}
return 0;
}

Output
Enter the Elements of the

Array 10 20 30 40 50

The Elements of the Array

are 10 20 30 40 50
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
e) Classification of Arrays
i. One-Dimensional Array
ii. Two-Dimensional Array
iii. Multi-Dimensional Array
SR
INSTITUTE OF
M SCIENCE AND
TECHNOLOGY,
CHENNAI.

2. 3 Arrays Contd...
i. One Dimensional Array
❑ Data stored under a single variable using one subscript
❑ 1-D Array Declaration – Syntax
datatype arrayname [size/subscript];
❑ Example: int a [5];
❑ 1-D Array initialization – Syntax
datatype arrayname [size] = { list of values};
Example: int a [5] = { 10, 20, 30, 40, 50};
/* Program 1 : One Dimensional Array*/
a
#include<stdio.h> a [10]
40
int main ( ) [0]
22
{ a
34
[1]
int a[10], n, i, sum; 12
a
clrscr( ); [2] 64
printf(“Enter the Number of a
[3]
Elements\n”); scanf(“%d”, &n);
a
for(i = 0; i < n; i++) [4]
a
{
[5] i
scanf(“%d”, & a [i]);
}
5a 0
[6]
sum = 0; a su
[7] m0
for(i = 0; i < n; i++)
a
/* Program 1 : One Dimensional Array*/
{ a
sum = sum + a[i]; a [10]
40
[0]
} 22
a
printf(“The Sum is: %d”, 34
[1]
12
sum); return 0; a
[2] 64
} a
[3]
Output a
Enter the Number of Elements [4]
5 a
40 22 34 12 64 [5] i
The Sum is 182 5a 4
[6]
a su
[7] m182
a
/* Program 2 : 1-D Array for
Sorting*/
#include<stdio.h>
int main( )
{
int i, j, temp, n, a[10];
printf(“Enter the Number of Elements:”);
scanf(“%d”, &n);
printf(“Enter the Elements to be Sorted\n”);
for(i=0; i<n; i++)
{
scanf(“%d\n”, &a[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i] >a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
print(“The Sorted Elements are:
\n”); for(i=0; i<n; i++)
{
printf(“%d\n”, a[i]);
}
return 0;
}
Output
Enter the Number of Elements:5
Enter the Elements to be Sorted
25
12
45
68
7
The Sorted Elements are:
7
12
25
45
68
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 4 - Initializing and Accessing 2D Array


An array of arrays is known as 2D array. The two dimensional
(2D) array in C programming is also known as matrix. A matrix
can be represented as a table of rows and columns.
The syntax to declare the 2D array is
data_type array_name[rows][columns];
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 4 - Initializing and Accessing 2D Array


Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if
the declaration and initialization are being done simultaneously.
However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The
two-dimensional array can be declared and defined in the
following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
/* Program 1 : 2-D Array */
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
/* Program 2 : 2-D Array Storing elements in a matrix and printing it*/
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....


56 10 30
34 21 34
45 56 78
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 5 - Pointer and address of operators


A pointer variable is another variable that holds the address of
the given variable to be accessed. Pointers provide a way of
accessing a variable with out referring to variable directly.
• Declaration: type *ptr_name;
• Initialiazation: int x, *p = & x;
• A pointer should be initialized before use.
• The unary operator * is termed as dereferencing operator or
indirection operator, as it allows to access the value of a
variable indirectly.
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 5 - Pointer and address of operators


Types of pointer
Null pointer: Null pointer is a constant with a value of zero
defined in several standard libraries.
Dangling pointer: If any pointer is pointing to any address at
given point in a program and later on the variable has been
deleted from that specific memory location, although the pointer
is still referencing to the memory location. These pointers are
called dangling pointers
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 5 - Pointer and address of operators


Types of pointer
Eg:
int *x, *y;
x = (int*) malloc(size of(int));
*y = 10;
x=y;
free(y);
SR
INSTITUTE OF SCIENCE
M AND TECHNOLOGY,
CHENNAI.

2. 5 - Pointer and address of operators


Genetic Pointers: Pointers which doesn’t have any specific data
type is known as genetic pointers.
Eg: void *the_data;
Wild Pointers: Uninitialized pointers are known as wild pointers
because they point to some arbitrary memory location and may
cause a program to crash or behave badly.
Eg: int main()
{
Int *ptr;
Printf(“%d”, *ptr);
}
/* Array Using Pointers */

#include<stdio.h> Output:
Int main() Enter elements: 1
{ 2
int data[5],I; 3
printf(“Enter elements: ”); 5
for(i=0;i<5;++i) 4
scanf(“%d”, data + i);
printf(“you entered: \n”); You entered: 1
for(i=0; i<5; i++) 2
printf(“%d”, *(data + i)); 3
return 0; 5
} 4
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 6 - Pointer Declaration and dereferencing


Declaration of Pointer Variable

Like normal variables, pointer variables must be declared before using them.
General syntax for declaring pointer variable is:

data type * pointer_name;

Examples of Declaration of Pointer:


int *ptr; Here ptr is a pointer variable and it is read as a pointer to integer since
it can point to integer variables.
float *fptr; Here fptr is a pointer variable and it is read as a pointer to float
since it can point to float variables.
Char *cp; Here cp is a pointer variable and it is read as a pointer to character
since it can point to character variable.
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 6 - Dereferencing of Pointer
❑ The operator * used in front of the name of the pointer variable is known as
pointer or dereferencing or indirection operator. After valid referencing
of pointer variable, *pointer_variable gives the value of the variable pointed
by pointer variable and this is known as dereferencing of pointer.

❑ For the sake of simplicity, *pointer_variable after referencing instructs


compilers that go to the memory address stored by pointer_variable and get
value from that memory address.
/* Examples of Dereferencing of Pointer*/

Int a = 5; Float val = 5.5;


Int *ptr; Float *p;
Ptr = & a; p = &val;
Printf(“a = % d, *ptr); Printf(“val = %f”, *p);

This prints a = 5 which is This prints val = 5.5 which is


accessed through pointer. accesed through pointer.
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 7 – Void Pointers
❑ A void pointer is a pointer that has no associated data type with it. A void
pointer can hold address of any type and can be typecasted to any type.

#include<stdio.h>
int main()
{
int a[2] = {1, 2};
void *ptr = &a;
ptr = ptr + sizeof(int);
printf("%d", *(int *)ptr);
return 0;
}
Output: 2
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 8 – Null Pointers
The null pointer is a constant with a value of zero defined in several
standard libraries.

#include<stdio.h>

int *ptr = NULL;

printf(“The value of ptr is: %d\n”, &ptr);

return 0;

}
SR
M
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 8 – Null Pointers
When the above code is compiled and executed, it produces the following
result:

The value of ptr is 0

On most of the operating system, programs are not permitted to


SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 9 – Pointer based Array Manipulation


Pointer and Arrays in C

When an array in C language is declared, compiler allocates sufficient


memory to contain all its elements. Its base address is also allocated
by the compiler.

Declare an array arr,

int arr[5] = { 1, 2, 3, 4, 5 };
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 9 – Pointer based Array Manipulation


Pointer and Arrays in C

Suppose the base address of arr is 1000 and each integer


requires two bytes, the five elements will be stored as follows:
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 9 – Pointer based Array Manipulation


Pointer and Arrays in C
Variable arr will give the base address, which is a constant
pointer pointing to arr[0]. Hence arr contains the address of
arr[0] i.e. 1000

arr has two purpose


• It is the name of the array
• It acts as a pointer pointing towards the first element in the
array.

arr is equal to &arr[0] by default


/* Examples of Pointers to Array*/
#include<stdio.h>
Void main()
{
int a[3] = {1,2,3}
int *p = a;
for(i=0; i<3; i++)
{
printf(“%d”, *p)
P++;
}
return 0;
}

Output:
123
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

2. 9 – Pointer based Array Manipulation


Pointer and Arrays in C
Replacing the printf(“%d”, *p); statement of the above example,
with below mentioned statements. Lets see what will be the
result.
printf(‘%d”, a[i]); prints the array, by incrementing index
printf(‘%d”, i[a]); this will also print elements of array
printf(‘%d”, a+i); this will prints address of all the array elements.
printf(‘%d”, *(a+i)); will print value of array element
printf(‘%d”, *a); will print value of a[0] only
a++ compile time error, we cannot change the base address of the
array.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
2. 9 – Pointer based Array Manipulation
Pointer and Arrays in C
Syntax:
*(a+i) //pointer with an array
is same as:
a[i]

Pointer to Multidimensional Array


Let's see how to make a pointer point to a multidimensional
array. In a[i][j], a will give the base address of this array, even a
+ 0 + 0 will also give the base address, that is the address of
a[0][0] element.
Syntax:
*(*(a + i) + j)
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
2. 9 – Pointer based Array Manipulation
Pointer and Character strings
Pointer is used to create strings. Pointer variables of char type
are treated as string.

char *str = "Hello";

The above code creates a string and stores its address in the
pointer variable str. The pointer str now points to the first
character of the string "Hello".

The string created using char pointer can be assigned a value at


runtime.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
2. 9 – Pointer based Array Manipulation
Pointer and Character strings

char *str;
str = "hello";
The content of the string can be printed using printf() and
puts()
printf("%s", str);
puts(str);

str is a pointer to the string and also name of the string.


Therefore we do not need to use indirection operator *.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
2. 9 – Pointer based Array Manipulation
Array of Pointers
Pointers are very helpful in handling character arrays with rows
of varying lengths.
char *name[3] = {
"Adam",
"chris",
"Deniel“
};
//without pointer
char name[3][20] = {"Adam", "chris", "Deniel"};
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
2. 9 – Pointer based Array Manipulation
Array of Pointers

In the second approach memory wastage is more, hence it


is preferred to use pointer in such cases.
THANK
YOU

You might also like