Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Unit III

Arrays, Strings and Pointers


ARRAY
An array is a collection of similar(Homogeneous) data elements. The elements of the array are
stored in consecutive memory locations and are referenced by an index

Syntax:
type name[size][][] …={values};
One Dimensional Array
Declaration: type array_name[size];
initialization: array_name={values};

Declaration & Initialization: type array_name[size]={values}; //values are


separated by comma
Example: int a[5]={10,20,30,40,50};
Print the values of for(int i =0;i<=10;i++)
Array Elements printf(marks[i]);
#include<stdio.h>
Arrays are used to store multiple void main()
values in a single variable, instead #include<stdio.h> {
of declaring separate variables for void main() int a[5],i,j,t;
each value { printf("Enter five values : \n");
int a[5],i,max; for(i=0;i<5;i++)
printf("Enter five values : \n"); scanf("%d",&a[i]);
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
scanf("%d",&a[i]); for(j=i+1;j<5;j++)
} {
max=a[0]; if(a[i]>a[j])
for(i=1;i<5;i++) {
{ t=a[i];
if(max<a[i]) a[i]=a[j];
{ a[j]=t;
max=a[i]; }
} }
} }
printf("Maximum no is %d",max); printf("Ascending order : \n");
} for(i=0;i<5;i++)
printf("%d\t",a[i]);
}
#include<stdio.h>
void main()
{
int a[20],i,search,n;
printf("How many elements?");
scanf("%d",&n);

printf("Enter array elements:n");


for(i=0;i<n;++i)
scanf("%d",&a[i]);

printf("nEnter element to search:");


scanf("%d",&search);

for(i=0;i<n;++i)
if(a[i]==search)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
}
2D Array: A two dimensional array is specified #include<stdio.h>
void main()
using two subscripts where one subscript denotes {
row and the other denotes column int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter values of Matrix A : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter values of Matrix B : \n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf("Added Matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
#include<stdio.h>
void main() printf("Matrix Multiplication\n");
{ for(i=0;i<3;i++)
int a[3][3],b[3][3],c[3][3],i,j; {
printf("Enter values of Matrix A : \n"); for(j=0;j<3;j++)
for(i=0;i<3;i++) printf("%d\t",c[i][j]);
for(j=0;j<3;j++) printf("\n");
scanf("%d",&a[i][j]); }
}
printf("Enter values of Matrix B : \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
3D Array: A three dimensional array is specified #include<stdio.h>
using three subscripts where first subscript denotes void main()
number of 2D arrays, second subscripts denotes row {
int i, j, k;
and the other denotes column int arr[3][3][3];
printf("Enter the Matrix 3D Array Values : \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
for(k=0;k<3;k++)
scanf("%d",&a[i][j][k]);
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
STRING #include <stdio.h>
void main()
String is a collection of characters {
int i = 0, count = 0;
Strings are defined as a null-terminated char s[100];
character array.
printf("Input a string\n");
string is terminated with a special NULL gets(s);
character \0.
while (s[i] != NULL) {
if (s[i] == 'a' || s[i] == 'A' || s[i] == 'e' || s[i] == 'E'
|| s[i] == 'i' || s[i] == 'I' || s[i] =='o' || s[i]=='O'
|| s[i] == 'u' || s[i] == 'U')
count++;
i++;
}

printf("Number of vowels in the string: %d", count);


}

• There are two ways to declare a string in c language.


• By char array Ex: char str[]={‘a’, ‘b’, ‘c’, ‘\0’};
• By string literal Ex: char str[]=“abc”;
UNFORMATTED INPUT AND OUTPUT
#include<stdio.h>
void main(){
char name[50];
printf("Enter your name: ");
gets(name);
printf("Your name is: ");
puts(name); //displays string
}

#include<stdio.h>
void main()
{
int c=getchar();
while(c!=EOF)
{
putchar(c);
c=getchar();
}
}
#include <stdio.h> #include <stdio.h>
#include <stdio.h>
#include <string.h> #include <string.h>
#include <string.h>
void main() int main()
int main()
{ {
{
char s1[30] = "Good Luck"; char s1[10] = "Hello";
char s1[20]="Kamaraj";
char s2[30] = "All of You !"; char s2[10] = "World";
char s2[40]="kamaraj";
strcpy(s1,s2); strcat(s1,s2);
if (strcmp(s1, s2) ==0) //-,+,0 value
printf("String s1 is: %s", s1); printf("string concatenation: %s", s1);
printf("s1 and s2 are equal");
int len=strlen(s1); }
else
printf("Length of s1 is: %d", len);
printf("s1 and s2 are different");
}
#include <stdio.h> }
#include <string.h>
void main()
#include<stdio.h> {
#include<string.h> char s1[10],s2[10];
void main() printf("Enter the string: ");
{ gets(s1);
char s[100]; strcpy(s2,s1);
printf("Enter a string: "); strrev(s2);
scanf("%[^\n]",s); if(!strcmp(s1,s2))
printf("In Lower Case:\n"); printf("string is palindrome");
puts(strlwr(s)); else
} printf("string is not palindrome");
}
#include <stdio.h>
int main() {

char a[10],b[10],rev[10];
int i,j;
printf("Enter the String:"); i=0;
gets(a); while(a[i]!='\0')
printf("Copying a string:"); {
for(i=0;a[i]!=NULL;i++) if(a[i]>='A' && a[i]<='Z')
b[i]=a[i];
a[i]=a[i]+32;
b[i]='\0';
puts(b); i++;
printf("length is %d",i); }
j=0; printf("Lower case is");
for(i=i-1;i>=0;i--) puts(a);
rev[j++]=a[i];
return 0;
rev[j]='\0';
printf("\nReversed String "); }
puts(rev);
Arrays of Strings #include <stdio.h>
int main ()
{
char s[5][10];
• Strings of Strings or an Arrays of Strings would store another individual string.
printf ("Enter the string");
for (int i = 0; i < 5; i++)
Syntax: char str_name[row_size][column_size];
scanf ("%s", s[i]);
row_size specifes the total number of strings column_size
printf ("Display String");
specifies length of the individual strings for (int i = 0; i < 5; i++)
printf ("\n%s", s[i]);
return 0;
}
Pointer
A pointer is a variable that stores the memory Pointer to Pointer: stores address of another pointer variable
address of another variable
Syntax: type *ptr=&variablename;
Example
int a=10;
int *p=&a; // stores the address of a
Benefits:
• Enables us to access a variable that is defined
outside the function. #include<stdio.h>
• Can be used to pass information back and void main()
{
forth between a function and its reference int num= 10;
point. int *ptr=&num;
#include<stdio.h>
• More efficient in handling data tables. printf("%d", *ptr);
} void main()
• Reduces the length and complexity of a {
char *ch = "Hello World";
program. printf("%s", ch);
• Sometimes also increases the execution }
speed.
ARRAY AND POINTER
When an array is declared,
#include <stdio.h>
• The compiler allocates a base address and sufficient amount of
int main ()
storage to contain all the elements of the array in contiguous {
memory locations. char *s[4];
• The base address is the location of the first element (index 0) of printf ("Enter the string");
the array. for (int i = 0; i < 4; i++)
• The compiler also defines the array name as a constant pointer to scanf ("%s", s[i]);
the first element.
printf ("Display String");
x  &x[0]  2500 ; for (int i = 0; i < 4; i++)
printf ("\n%s", s[i]);
p = x; and p = &x[0]; are equivalent. return 0;
We can access successive values of x by using p++ }
or p- - to move from one element to another.
Relationship between p and x: *(p+i) x[i] Array of Strings
p = &x[0] = 2500 char *str[4] = {
p+1 = &x[1] = 2504 "String",
p+2 = &x[2] = 2508 "Topics",
"Pointers",
p+3 = &x[3] = 2512 "World"
p+4 = &x[4] = 2516 };
Pointer Expressions / Arithmetic
Like other variables, pointer variables can be used in expressions. Data Type Scale Factor
If p1 and p2 are two pointers, the following statements are valid: char 1
int 4
sum = *p1 + *p2 ;
float 4
prod = *p1 * *p2 ;
double 8
prod = (*p1) * (*p2) ; If p1 is an integer pointer, then
*p1 = *p1 + 2; p1++
x = *p1 / *p2 + 5 ; will increment the value of p1 by 4.
We have seen that an integer value can be added to or subtracted
from a pointer variable.
int *p1, *p2 ; #include<stdio.h>
void main()
int i, j; {
p1 = p1 + 1 ; int arr[5] = { 1, 2, 3, 4, 5 };
p2 = p1 + j ; int *ptr = arr;
for(int i=0;i<5;i++)
p2++ ; printf("%d",*(ptr+i));
p2 = p2 – (i + j) ; }
In reality, it is not the integer value which is added/subtracted, but
rather the scale factor times the value.
#include<stdio.h> #include<stdio.h>
void swap(int,int); void swap(int *a,int *b);
void main() void main()
{ {
int a,b; int a,b;
printf(“enter the a & b”); printf(“enter the a & b”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&a,&b);
printf(“A is %d B is %d”,a,b); printf(“A is %d B is %d”,a,b);
swap(a,b); swap(&a,&b);
printf(“A is %d B is %d”,a,b);
} }
void swap(int a, int b)
{ void swap(int *a, int *b)
int t=a; {
a=b; int t=*a;
b=t; *a=*b;
printf(“A is %d B is %d”,a,b); *b=t;
} }
Function Pointers
1) Unlike normal pointers, a function pointer points to code, #include <stdio.h>  
not data. Typically a function pointer stores the start of int add(int,int);  
executable code. int main()  
{  
2) Unlike normal pointers, we do not allocate de-allocate    int a,b;  
memory using function pointers.    int (*ip)(int,int);  
3) A function’s name can also be used to get functions’    int result;  
   printf("Enter the values of a and b : ");  
address. For example, in the below program, we have    scanf("%d %d",&a,&b);  
removed address operator ‘&’ in assignment. We have also    ip=add;  
changed function call by removing *, the program still works.    result=(*ip)(a,b);  
   printf("Value after addition is : %d",result);  
1.Declaration of a function pointer.       return 0;  
type *fp(type,..); }  
float (*fp) (int , int);  int add(int a,int b)  
{  
2. Declaration of  function.       int c=a+b;  
type func(type,..);     return c;  
float func( int , int );   }  

3. Assigning address of func to the fp pointer
fp=func;
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = fun; // & removed

fun_ptr(10); // * removed

return 0;
}
int main()
#include <stdio.h> {
void add(int a, int b) // fun_ptr_arr is an array of function pointers
{ void (*fun_ptr_arr[])(int, int) = {add, sub, mul};
printf("Addition is %d\n", a+b); unsigned int ch, a = 15, b = 10;
}
void sub(int a, int b) printf("Enter Choice: 0 for add, 1 for sub & 2 fo
{ multiply\n");
printf("Subtraction is %d\n", a-b); scanf("%d", &ch);
}
void mul(int a, int b) if (ch > 2) return 0;
{
printf("Multiplication is %d\n", a*b); (*fun_ptr_arr[ch])(a, b);
}
}
A null pointer which is a special pointer value that is known not to point
anywhere. This means that a NULL pointer does not point to any valid memory
address.
To declare a null pointer you may use the predefined constant NULL,
int *ptr = NULL;

GENERIC POINTER
• A generic pointer is pointer variable that has void as its
data type. #include<stdio.h>
void main()
• The generic pointer, can be pointed at variables of any {
data type. int x=10;
• It is declared by writing char ch = ‘A’;
void *gp;
void *ptr; gp = &x;
• You need to cast a void pointer to another kind of printf("\n integer value = %d", *(int*)gp);
pointer before using it. gp = &ch;
printf("\n the character %c", *(char*)gp);
• Generic pointers are used when a pointer has to point to }
data of different types at different times.
Dynamic Memory Allocation is a process in which allocate or
deallocate a block of memory during the run-time of a program.
#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
int main() int main()
{ {
int i, n; int i, n;
int *arr; int *arr;
printf("\n Enter the number of elements: "); printf("\n Enter the number of elements: ");
scanf("%d", &n); scanf("%d", &n);
arr = (int*)malloc(n*sizeof(int)); arr = (int*)calloc(n,sizeof(int));
for (i=0; i<n;i++) for (i=0; i<n;i++){
{ printf("\n Enter the value of %d of the array:",i);
printf("\n Enter the value of %d of the array:",i); scanf("%d",&arr[i]);
scanf("%d",&arr[i]); }
} printf("\n The array contains \n");
printf("\n The array contains \n"); for (i=0; i<n;i++)
for (i=0; i<n;i++) printf("%d",arr[i]);
printf("%d",arr[i]); free(arr);
return 0; return 0;
} }
#include <stdio.h>
#include <stdlib.h>
int main() { // rellocating the memory
int *ptr, i , n1, n2; ptr = realloc(ptr, n2 * sizeof(int));
printf("Enter size: "); for (i=0; i<n2;i++)
scanf("%d", &n1); {
ptr = (int*) malloc(n1 * sizeof(int)); printf("\n Enter the value of %d of the
for (i=0; i<n1;i++) array:",i);
{ scanf("%d",&ptr[i]);
printf("\n Enter the value of %d of the }
array:",i); printf("\n The array contains \n");
scanf("%d",&ptr[i]); for (i=0; i<n2;i++)
} printf("%d",ptr[i]);
printf("\n The array contains \n"); free(ptr);
for (i=0; i<n1;i++) return 0;
printf("%d",ptr[i]); }
printf("\nEnter the new size: ");
scanf("%d", &n2);

You might also like