Unit 4[1]-1
Unit 4[1]-1
Introduction of Array
Pointer and Arrays
Array of Functions
String
Need of Array Variable
Suppose we need to store rollno of the student in the integer variable.
Declaration
int rollno;
Now we need to store rollno of 100 students.
Declaration
int rollno101, rollno102, rollno103,
rollno104...;
This is not appropriate to declare these many integer variables.
e.g. 100 integer variables for rollno.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
Fixed Size: We define the size at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList
Declaring an array
Syntax
By default array index starts with
data-type variable-
name[size]; 0.
Integer Array [0] [1] [2] [3] [4] If we declare an array of size 5
int mark[5]; then its index ranges from 0 to 4.
First element will be store at
integer
mark[0] and last element will be
stored at mark[4] not mark[5].
Float Array [0] [1] [2] [3] [4] Like integer and float array we can
float avg[5] declare array of type char.
;
float
Initialing and Accessing an Array
Declaring, initializing and accessing single integer variable
int mark=90; //variable mark is initialized with value 90
printf("%d",mark); //mark value printed
Declaring, initializing and accessing integer array variable
int mark[5]={85,75,76,55,45}; //mark is initialized with 5 values
printf("%d",mark[0]); //prints 85
printf("%d",mark[1]); //prints 75
printf("%d",mark[2]); //prints 65
printf("%d",mark[3]); //prints 55
printf("%d",mark[4]); //prints 45
[0] [1] [2] [3] [4]
mark[5]
85 75 65 55 45
Read(Scan) Array Elements
Reading array without loop Reading array using loop
void main() void main()
{ {
int mark[5]; int mark[5],i;
printf("Enter array element="); for(i=0;i<5;i++)
scanf("%d",&mark[0]); {
printf("Enter array element="); printf("Enter array element=");
scanf("%d",&mark[1]); scanf("%d",&mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[2]); for(i=0;i<5;i++)
printf("Enter array element="); {
scanf("%d",&mark[3]); printf("%d",mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[4]); }
printf("%d",mark[0]);
printf("%d",mark[1]);
printf("%d",mark[2]); [0] [1] [2] [3] [4]
printf("%d",mark[3]); mark[5]
printf("%d",mark[4]); } 85 75 65 55 45
Develop a program to count number of positive or negative number from an array of 10 Number
Program
void main(){
int num[10],i,pos,neg; Output
pos = 0; Enter array element=1
neg = 0; Enter array element=2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
printf("Enter array element="); Enter array element=5
scanf("%d",&num[i]); Enter array element=-1
} Enter array element=-2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
if(num[i]>0) Enter array element=5
pos=pos+1; Positive=8,Negative=2
else
neg=neg+1;
}
printf("Positive=%d,Negative=
Two dimensional Array in C
Two dimensional Array in C
Syntax
A two dimensional array can be seen as a
data-type variable-name[x][y];
table with ‘x’ rows and ‘y’ columns.
Declaration The row number ranges from 0 to (x-1) and
int data[3][3]; // column number ranges from 0 to (y-1).
This array can hold 9 elements
printf("%d",data[2][0]);//7
printf("%d",data[2][1]); //8
printf("%d",data[2][2]); //9
// data[3][3]
can be initialized like this also
Read(Scan) 2D Array Elements
Program
void main(){
int data[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ Output Enter array element=1
printf("Enter array element=" Enter array element=2
); Enter array element=3
scanf("%d",&data[i][j]); Enter array element=4
} Enter array element=5
} Enter array element=6
for(i=0;i<3;i++) Enter array element=7
{ Enter array element=8
for(j=0;j<3;j++) Enter array element=9
{ 1 2 3
printf("%d",data[i][j]); 4 5 6
} 7 8 9
Develop a program to count number of positive, negative and zero elements from 3 X 3 matrix
Program
Output
void main(){
Enter array element=9
int data[3][3],i,j,pos=0,neg=0,zero=0;
Enter array element=5
for(i=0;i<3;i++)
Enter array element=6
{
Enter array element=-3
for(j=0;j<3;j++)
Enter array element=-7
{
Enter array element=0
printf("Enter array element=");
Enter array element=11
scanf("%d",&data[i][j]);
Enter array element=13
if(data[i][j]>0)
Enter array element=8
pos=pos+1;
positive=6,negative=2,zero
else if(data[i][j]<0)
=1
neg=neg+1;
else
zero=zero+1;
}
}
printf("positive=%d,negative=%d,zero=
Declaration & Initialization of Pointer
Syntax
p is integer pointer variable
datatype *ptr_variablename; & is address of or referencing operator which
Example returns memory address of variable.
void main() * is indirection or dereferencing operator which
{ returns value stored at that memory address.
int a=10, *p; // assign memory address & operator is the inverse of * operator
of a to pointer variable p x = a is same as x = *(&a)
p = &a;
printf("%d %d %d", a, *p, p);
}
Output
10 10 5000
Why use Pointer?
C uses pointers to create dynamic data structures, data structures built
up from blocks of memory allocated from the heap at run-time.
Example linked list, tree, etc.
C uses pointers to handle variable parameters passed to functions.
Pointers in C provide an alternative way to access information stored in
arrays.
Pointer use in system level programming where memory addresses are
useful. For example shared memory used by multiple threads.
Pointers are used for file handling.
This is the reason why C is versatile.
Pointer to Pointer – Double Pointer
Pointer holds the address of another variable of same type.
When a pointer holds the address of another pointer then such type of
pointer is known as pointer-to-pointer or double pointer.
The first pointer contains the address of the second pointer, which points
to the location that contains the actual value.
Syntax Pointer Pointer Variable
datatype
**ptr_variablename;
int **ptr;
address address value
Write a program to print variable, address of pointer variable and pointer to pointer variable.
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; // address of var
pptr = &ptr; // address of ptr using address of operator &
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Relation between Array & Pointer
When we declare an array, compiler allocates continuous blocks of
memory so that all the elements of an array can be stored in that
memory.
The address of first allocated byte or the address of first element is
assigned to an array name.
Thus array name works as pointer variable.
The address of first element is also known as base address.
2018
Relation between Array & Pointer – Cont.
Example: int a[10], *p;
a[0] is same as *(a+0), a[2] is same as *(a+2) and a[i] is same as *(a+i)
Syntax
datatype *name[size];
2018
int *ptr[5]; //declares an array of integer pointer of size 5
#include <stdio.h>
int main() {
// Array of pointers to strings
const char *fruits[] = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
// Size of the array
int size = sizeof(fruits) / sizeof(fruits[0]);
// Printing each string using the array of pointers
printf("List of fruits:\n");
for (int i = 0; i < size; i++) {
printf("%s\n", fruits[i]);
}
return 0;
}
Relation between Array & Pointer
When we declare an array, compiler allocates continuous blocks of
memory so that all the elements of an array can be stored in that
memory.
The address of first allocated byte or the address of first element is
assigned to an array name.
Thus array name works as pointer variable.
The address of first element is also known as base address.
2018
Array of Pointer – Cont.
An array of pointers ptr can be used to point to different rows of matrix as
follow:
for(i=0; i<5; i++)
{
ptr[i]=&mat[i][0];
}
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10
] \
C O M P U T E R
0
String declaration and initialization
There are two ways to declare a Initialization method 1:
string in c language. char name[10]={‘C',‘O',‘M',‘P',‘U',‘T',‘E',’
By char array R’,'\0'};
By string literal
Initialization method 2:
Declaration char name[10]=“COMPUTER";
char name[10] //'\
; 0' will be automatically inserted at the end in th
is type of declaration.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
C O M P U T E R \0
name[10
]
Difference between char array and string literal
In C, there are two main differences between // Character array without explicit null
a character array and a string literal: character
1.Null Character ('\0) char arr1[] = {'H', 'e', 'l', 'l', 'o'}; // Not null-
•Character Array: When you create a terminated, not a proper string
character array, you must explicitly include char arr2[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Proper
the null character ('\0') to mark the end of null-terminated string
the string if not using a string initializer. // String literal
•String Literal: When using a string literal, char arr3[] = "Hello"; // Null character '\0'
the compiler automatically appends the added automatically by the compiler
null character ('\0') to signify the end of the
string.
// Character array
Mutability: char arr[] = "Hello";
•Character Array: You can modify arr[0] = 'M'; // This is allowed
the contents of a character array printf("%s\n", arr); // Output: Mello
after its declaration.
•String Literal: A string literal is // String literal
char *str = "Hello";
stored in read-only memory, and // str[0] = 'M'; // This leads to undefined
modifying it is undefined behavior and may cause a crash
behavior. printf("%s\n", str); // Safe as long as you don't
modify the literal
Read String: scanf()
void main()
Output
{
char name[10]; Enter name: Parul
printf("Enter name:"); Name=Parul
scanf("%s",name); Output
printf("Name=%s",name);
Enter name: CSE Parul
}
Name=CSE
There is no need to use address of (&) operator in scanf to store a string.
As string name is an array of characters and the name of the array, i.e., name
indicates the base address of the string (character array).
scanf() terminates its input on the first whitespace(space, tab, newline etc.)
encountered.
Read String: gets()
#include<stdio.h> Output
void main()
{ Enter name:Parul
char name[10]; University Name=Parul
printf("Enter name:"); University
gets(name); //
read string including white spaces
printf("Name=%s",name);
}
gets(): Reads characters from the standard input and stores them as a string.
puts(): Prints characters from the standard.
scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
gets(): Does not stop reading input when it encounters whitespace instead it
takes whitespace as a string.
String Handling Functions : strlen()
C has several inbuilt functions to operate on string. These functions are known
as string handling functions.
strlen(s1): returns length of a string in integer
Program
#include <stdio.h> Output
#include <string.h> //header file for string functions Enter string: Parul
void main() University
{ 15
char s1[10];
printf("Enter string:");
gets(s1);
printf("%d",strlen(s1)); // returns length of s1 in in
teger
}
String Handling Functions: strcmp()
strcmp(s1,s2): Returns 0 if s1 and s2 are the same.
Returns less than 0 if s1<s2.
Returns greater than 0 if s1>s2.
Program
void main() Output
{ Enter string-
char s1[10],s2[10]; 1:Computer
printf("Enter string-1:"); Enter string-
gets(s1); 2:Computer
printf("Enter string-2:"); Output
Strings are same
gets(s2); Enter string-
if(strcmp(s1,s2)==0) 1:Computer
printf("Strings are same"); Enter string-
else 2:Computer
printf("Strings are not same");} Strings are same
String Handling Functions
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1,"he"));
Output : heir
strcat(s1,s2) Appends 2nd string at the end of 1st string.
strcat(s1,s2); a copy of string s2 is appended at the end of string s1. Now s1
becomes “TheirThere”
strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1,'i'));
Output : ir