0% found this document useful (0 votes)
2 views

aray notes revised

An array in C is a fixed-size collection of similar data types stored in contiguous memory locations, categorized into one-dimensional and multidimensional arrays. Key properties include fixed size, homogeneous collection, and random access, while advantages involve fast access and ease of traversal, and disadvantages include fixed capacity and costly insertions/deletions. Arrays must be declared before use, and can be initialized in various ways, with specific syntax for one-dimensional and multi-dimensional arrays.

Uploaded by

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

aray notes revised

An array in C is a fixed-size collection of similar data types stored in contiguous memory locations, categorized into one-dimensional and multidimensional arrays. Key properties include fixed size, homogeneous collection, and random access, while advantages involve fast access and ease of traversal, and disadvantages include fixed capacity and costly insertions/deletions. Arrays must be declared before use, and can be initialized in various ways, with specific syntax for one-dimensional and multi-dimensional arrays.

Uploaded by

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

What is Array in C?

An array in C is a fixed-size collection of similar data items stored in contiguous


memory locations. It can be used to store the collection of primitive data types
such as int, char, float, etc., and also derived and user-defined data types such
as pointers, structures, etc.

Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as
follows:

One Dimensional Arrays (1D Array)


Multidimensional Arrays
1. One Dimensional Array in C
The One-dimensional arrays, also known as 1-D arrays in C are those arrays that
have only one dimension.

2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension.
Some of the popular multidimensional arrays are 2D arrays and 3D arrays. We can
declare arrays with more dimensions than 3d arrays but they are avoided as they get
very complex and occupy a large amount of space.

A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions. They can be visualized in the form of rows and columns organized in a
two-dimensional plane.

Syntax of 2D Array in C
array_name[size1] [size2];

B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D
Array. A 3D array has exactly three dimensions. It can be visualized as a
collection of 2D arrays stacked on top of each other to create the third dimension.

Syntax of 3D Array in C
array_name [size1] [size2] [size3];

Properties of Arrays in C
It is very important to understand the properties of the C array so that we can
avoid bugs while using it. The following are the main properties of an array in C:

1. Fixed Size
The array in C is a fixed-size collection of elements. The size of the array must
be known at the compile time and it cannot be changed once it is declared.

2. Homogeneous Collection
We can only store one type of element in an array. There is no restriction on the
number of elements but the type of all of these elements must be the same.

3. Indexing in Array
The array index always starts with 0 in C language. It means that the index of the
first element of the array will be 0 and the last element will be N – 1.

4. Dimensions of an Array
A dimension of an array is the number of indexes required to refer to an element in
the array. It is the number of directions in which you can grow the array size.
5. Contiguous Storage
All the elements in the array are stored continuously one after another in the
memory. It is one of the defining properties of the array in C which is also the
reason why random access is possible in the array.

6. Random Access
The array in C provides random access to its element i.e we can get to a random
element at any index of the array in constant time complexity just by using its
index number.

7. No Index Out of Bounds Checking


There is no index out-of-bounds checking in C/C++, for example, the following
program compiles fine but may produce unexpected output when run.

//ARRAY
//DECLATION-INITIALISATION-ACCESSING ELEMENTS IN AN ARRAY

C Array Declaration
In C, we have to declare the array like any other variable before using it. We can
declare an array by specifying its name, the type of its elements, and the size of
its dimensions. When we declare an array in C, the compiler allocates the memory
block of the specified size to the array name.

Syntax of Array Declaration

data_type array_name [size];


or
data_type array_name [size1] [size2]...[sizeN];

// C Program to illustrate the array declaration


#include <stdio.h>

int main()
{

// declaring array of integers


int arr_int[5];
// declaring array of characters
char arr_char[5];

return 0;
}

C Array Initialization

There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration

data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size

data_type array_name[] = {1,2,3,4,5};

3. Array Initialization after Declaration (Using Loops)

for (int i = 0; i < N; i++)


{
array_name[i] = valuei;
}

//#################################################### TRAVERSAL
######################################//
//#include<stdio.h>
//int main()
//{
//int i,a[10]={10,9,8,7,6,5,4,3,2,1};
//for(i=0;i<10;i++)
//printf("%d",a[i]);
//return 0;
//}
//

//TO ACCESS (FOURTH)PARTICULAR ELEMENT IN AN ARRAY


//#include<stdio.h>
//int main()
//{
//int i,a[10]={10,9,8,7,6,5,4,3,2,1};
//for(i=0;i<10;i++)
//printf("%d",a[5]);
//return 0;
//}
//CODE TO INITIALIZE EACH ELEMENT OF ARRAY TO -1
//#include<stdio.h>
//int main()
//{
//int i,a[10];
//for(i=0;i<10;i++)
//{
//a[i]=-1;
//printf("%d",a[i]);
//}
//return 0;
//}

//READ AND DISPLAY N ELEMENTS USING ARRAY


//#include<stdio.h>
//int main()
//{
//int i=0,n,a[10];
//printf("enter no. of elements");
// scanf("%d",&n);
//for(i=0;i<10;i++)
//{
//printf("\n a[%d]= ",i);
//scanf("%d",&a[i]);
//}
//printf("\n the elments are:");
//for(i=0;i<10;i++)
// printf("a[%d]=%d\t",i,a[i]);

//return 0;
//}

//find mean of N ELEMENTS OF AN ARRAY

//#include<stdio.h>

//int main()
//{
// int i,n,a[5],sum=0,mean=0;
//printf("enter no.of elements in an array ");
//scanf("%d",&n);
//for(i=0;i<5;i++)
//{
//printf("\n a[%d]=",i);
//scanf("%d",&a[i]);
//}
//for(i=0;i<5;i++)
//sum=sum+a[i];
//mean=sum/n;
//printf("sum of an array is %d",sum);

//printf("\n mean of an array is %d",mean);


//return 0;
//}

//CODE TO FIND SMALLEST ELEMENT IN AN ARRAY


//#include<stdio.h>
//int main()
//{
//int i,n,a[10],smallest=-1111;
//printf("enter no. of elements in an array");
//scanf("%d",&n);
//for(i=0;i<n;i++)
//{
//printf("a[%d]=",i);
// scanf("%d",&a[i]);
// }
//for(i=0;i<n;i++)
//{
// if(a[i]<smallest)
//{
// smallest=a[i];
//}
//printf("the smallest no. is :%d",smallest);
//return 0;
//}
//}

//WAP TO PRINT THE POSITION OF SMALLEST OF N NUMBERS USING ARRAYS

//#include<stdio.h>
//int main()
//{
// int n,i,a[50],pos=-1,small=111;
// printf("enter no. of elements in an array");
//scanf("%d",&n);
//for(i=0;i<n;i++)
//{
// printf("a[%d]=",i);
//scanf("%d",&a[i]);
//}
//for(i=0;i<n;i++)
//{
//if(a[i]<small)
// {
// small=a[i];
// pos=i;
//}
//}
// printf("\n smallest no. is :%d",small);
//printf("\n position of smallest no. is :%d",pos);
//return 0;
//}
//WAP TO INTERCHANGE THE LARGEST AND THE SMALLEST NUMBER IN AN ARRAY
//#include<stdio.h>
//int main()
// {
// int i,n,a[50],largest=-1,small=1111,small_pos=0,largest_pos=0,temp;
// printf("enter no. of elements in an array ");
// scanf("%d",&n);
// for(i=0;i<n;i++)
// {
// printf("a[%d]=",i);
// scanf("%d",&a[i]);
// }
// for(i=0;i<n;i++)
// {
// if(a[i]<small)
// {
// small=a[i];
// small_pos=i;
// }
// }
// for(i=0;i<n;i++)
// {
// if(a[i]>largest)
// {
// largest=a[i];
// largest_pos=i;
//}
// }
// printf("\n smallest no. is %d",small);
// printf("\n position of smallest no. is %d ",small_pos);
// printf("\n largest no. is %d",largest);
// printf("\n position of largest no. is %d ",largest_pos);
//
// temp=a[largest_pos];
// a[largest_pos]=a[small_pos];
// a[small_pos]=temp;
// printf("new array is ");
// for(i=0;i<n;i++)
// printf("\n a[%d]=%d",i,a[i]);
//return 0;
//}

//WAP TO READ MARKS OF 10 STUDENTS IN THE RANGE OF 0-100 .THEN MAKE 10 GROUPS 0-
10,10-20,....SO ON .
//COUNT NUMBER OF VALUES THAT FALLS IN EACH GROUP AND DISPLAY THE RESULT

//#include<stdio.h>
//int main()
//{
// int i,n,marks[100],group[10]={0},count=0;

// printf("enter marks of 10 students:\n");

// for(i=0;i<10;i++)
//{
//printf("marks[%d]= ",i);
//scanf("%d", &marks[i]);
//++group[(int)(marks[i])/10]; //GROUP() GROUPS THE ELEMENT OF CALLING
ARRAY ACCORDING TO THE STRING VALUES RETURNED BY A PROVIDED TESTING FUNCTION.....
//}
//printf("\n group \t\t frequency "); // "\t" USED FOR COUPLE OF SPACES IN
SAME LINE
//for(i=0;i<=10;i++)
//{
// printf(" \n %d \t\t %d,i,group[i]");
//}

// return 0;
//}

//############################################################# INSERTION
#################################################################################//

//INSERTION OF ELEMENT AT DESIRED LOACTION IN AN ARRAY


//#include<stdio.h>
//int main()
//{
// int n,i,a[10],num,pos;
//printf("enter no. of elements in an array");
//scanf("%d",&n);
//for(i=0;i<n;i++)
//{
// printf("\n enter the values:");
//scanf("%d",&a[i]);
//}
//printf("\n enter the value to be inserted:");
//scanf("%d",&num);

// printf("\n enter position where you want to insert value:");


// scanf("%d",&pos);
//for(i=n-1;i>=pos-1;i--)
//{
// a[i+1]=a[i];
//}
//a[pos-1]=num;
//n++;

//for(i=0;i<n+1;i++)
// printf("%d",a[i]);

//return 0;
//}

//
###############################################################DELETION############
###############################################################################
//DELETE A NO. FROM A GIVEN LOCATION
//#include<stdio.h>
//int main()
//{
// int n,i,a[10],num,pos;
//printf("enter no. of elements in an array");
//scanf("%d",&n);
//for(i=0;i<n;i++)
//{
// printf("\n enter the values:");
//scanf("%d",&a[i]);
//}
// printf("\n enter the value to be deleted:");
//scanf("%d",&num);

//printf("\n enter position where you want to delete value:");


//scanf("%d",&pos);
//for(i=pos-1;i<n-1;i++)
//{
// a[i]=a[i+1];
//}
//n--;

//for(i=0;i<n+1;i++)
// printf("%d",a[i]);
//return 0;
//}

//
################################################MERGING############################
#######################################

//MERGING TWO UNSORTED ARRAYS


//#include<stdio.h>
//int main()
//{
// int i,n1,n2,n3,a1[10],a2[10],a3[30],m;
//printf("enter no. of elements in array1:");
//scanf("%d",&n1);
//for(i=0;i<n1;i++)
//{
// printf("enter elements in array");
//scanf("%d",&a1[i]);
//}
//printf("enter no. of elements in array2:");
//scanf("%d",&n2);
//for(i=0;i<n2;i++)
//{
// printf("enter elements in array");
//scanf("%d",&a2[i]);
//}
//m=n1+n2;
//for(i=0;i<n1;i++)
//{
// a3[i]=a1[i];
//}
//for(i=0;i<n2;i++)
//{
// a3[i]=a2[i];
//}
//printf("the merged array is %d");
//for(i=0;i<m;i++)
//{
// printf("%d",a3[i]);
//}
//return 0;
//}

//############################2D
ARRAYS#####################################################
//
###################################################################################
#######

//DECLARATION OF 2D ARRAY
//data_type_name[row size][column size];
//int marks[3][5];

//INITIALIZATION OF 2D ARRAY(compile time)


//int[2][3]={90,10,20,30,40,70};

//INITIALISING ENTIRE ARRAY =0


//int [2][3]={0};

//if some values are missing in an array then are initialised as 0

//ACCESING ELEMENTS IN 2D ARRAY


//SINCE 2D ARRAY CONTAIN TWO SUBSCRIPTS (i.e rows and columns)
//In 2D array we use two for loops......
// first for each rows in 2D array
//similarly second for each column

//individual elements of 2D array can be initialized using assignment operator


//marks[1][2]=80;or
//marks[1][2]=marks[1][1]+10;

//IN ORDER TO INPUT VALUES FROM KEYBOARD


//for(i=0;i<2;i++)
//for(j=0;j<2;j++)
//scanf("%d",&a[i][j];
//WAP TO PRINT ELEMENT OF 2D ARRAY
//#include<stdio.h>
//int main()
//{
// int i,j,n,a[2][2];

//printf("enter elements in array");


//scanf("%d",&n);

//for(i=0;i<2;i++)
//{
// for(j=0;j<2;j++)
//{
// scanf("%d",&a[i][j]);
//}
//printf("\n the elements of the matrix are: \n");
//for(i=0;i<2;i++)
//{
// printf("\n");
//for(j=0;j<2;j++)
// printf("\t %d %d",i,j,a[i][j]);
//}
//}

//return 0;
//}

Advantages of Array in C
The following are the main advantages of an array:

-Random and fast access of elements using the array index.


-Use of fewer lines of code as it creates a single array of multiple elements.
-Traversal through the array becomes easy using a single loop.
-Sorting becomes easy as it can be accomplished by writing fewer lines of code.

Disadvantages of Array in C
-Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
-Insertion and deletion of elements can be costly since the elements are needed to
be rearranged after insertion and deletion.

//#######################################################################
//########################## STRINGS ####################################

A String in C programming is a sequence of characters terminated with a null


character ‘\0’. The C String is stored as an array of characters. The difference
between a character array and a C string is the string is terminated with a unique
character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional array. Below is
the basic syntax for declaring a string.

char string_name[size];

C String Initialization
A string in C can be initialized in different ways. We will explain this with the
help of an example. Below are the examples to declare a string with the name str
and initialize it with “GeeksforGeeks”.

Ways to Initialize a String in C


We can initialize a C string in 4 different ways which are as follows:

1. Assigning a string literal without size


String literals can be assigned without size. Here, the name of the string str acts
as a pointer because it is an array.

char str[] = "GeeksforGeeks";


2. Assigning a string literal with a predefined size
String literals can be assigned with a predefined size. But we should always
account for one extra space which will be assigned to the null character. If we
want to store a string of size n then we should always declare a string with a size
equal to or greater than n+1.

char str[50] = "GeeksforGeeks";


3. Assigning character by character with size
We can also assign a string character by character. But we should remember to set
the end character as ‘\0’ which is a null character.

char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};


4. Assigning character by character without size
We can assign character by character without size with the NULL character at the
end. The size of the string is determined by the compiler automatically.

char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};


Note: When a Sequence of characters enclosed in the double quotation marks is
encountered by the compiler, a null character ‘\0’ is appended at the end of the
string by default.

How to Read a String Separated by Whitespaces in C?


We can use multiple methods to read a string separated by spaces in C. The two of
the common ones are:

We can use the fgets() function to read a line of string and gets() to read
characters from the standard input (stdin) and store them as a C string until a
newline character or the End-of-file (EOF) is reached.
We can also scanset characters inside the scanf() function
1. Example of String Input using gets()

// C program to illustrate
// fgets()
#include <stdio.h>
#define MAX 50
int main()
{
char str[MAX];

// MAX Size if 50 defined


fgets(str, MAX, stdin);

printf("String is: \n");

// Displaying Strings using Puts


puts(str);

return 0;
}

Standard C Library – String.h Functions


The C language comes bundled with <string.h> which contains some useful string-
handling functions. Some of them are as follows:

Function Name Description


strlen(string_name) Returns the length of string name.
strcpy(s1, s2) Copies the contents of string s2 to string s1.
strcmp(str1, str2) Compares the first string with the second string. If
strings are the same it returns 0.
strcat(s1, s2) Concat s1 string with s2 string and the result is stored in the
first string.
strlwr() Converts string to lowercase.
strupr() Converts string to uppercase.
strstr(s1, s2) Find the first occurrence of s2 in s1.

//IN c, string is a sequence of characters terminated by null character


//this means after last character ,a null character '\0' is stored to signify end
of character array

//IN CASE OF HELLO


//1000,1001,1002......are memory addresses of individual characters .....here we
can see 'H' is stored at memory location 1000
//but in reality ASCII CODES OF CHARACTERS ARE STORED IN MEMORY AND NOT CHARACTERS
ITSELF

//i.e 72 will be stored at address 1000

//INITIALISATION OF STRING

// char str[size];
//for example- In char str[100]....we can store a maximum of 99 usable characters
as last character is null character

//OTHER WAY OF INITIALISING STRING


//char str[]={'H','E','L','L','O','\0'};
//OBSERVE HERE WE HAVE NOT MENTIONED SIZE OF STRING SO WE USED NULL CHARACTER AT
END

//char str[10]="HELLO"
//OBSERVE HERE WE HAVE MENTIONED SIZE 10 SO COMPILER CREATES ARRAY OF SIZE
10 ...STORES STRING AND FINALLY TERMINATES STRING BY '/0'NULL CHARACTER

//An array name cannot be used as left operand of an assignment operator,


//these types of statements are illegal in c

//char str2,str1[]="hi";
//str2=str1;

//In C programming, the %c and %s are format specifiers used to display the values
of variables in a formatted output.

//The %c format specifier is used to print a single character. It expects an


argument of type char, and it prints the corresponding character to the output
screen.
//For example, the following code will print the character 'A' to the output
screen:

//char ch = 'A';
//printf("The character is %c", ch);

//The %s format specifier, on the other hand, is used to print a string. It expects
an argument of type char*, which is a pointer to an array of characters (i.e., a
string).
// The printf function prints the characters in the string until it reaches a null
character '\0',
// which indicates the end of the string. For example, the following code will
print the string "hello" to the output screen:

//char str[] = "hello";

//printf("The string is %s", str);

//READING THE STRING

//string can be read from user by using three ways


//1-USING scanf() function
// scanf("%s",str);

//2-using gets() function


// gets(str);
//gets() is automatically terminated with a null character

//main problem with scanf() is that it terminates as soon as it find blank spaces
//for example if string contains "HELLO WORLD" it will only print "HELLO".

//3-using getchar(),getch(),or getche() function repeatedly


//WRITING STRING

//the string can be displayed on screen using three ways:


//1-printf()
// printf("%d",str);
// '&' operand with string variable in the scanf statement generates
ERROR
//2-puts()
// puts(str);
//3-putchar()
// putchar(str[i]);

//NOTE::printf("\n %s",&str[2];//prints llo


//this is possible because a string is an array of characters.

//PROGRAM TO READ AND DISPLAY THE STRING


//#include<stdio.h>
//int main()
//{
// char str[10];
// printf("enter your name");
// gets(str);
// printf("entered string is %s",str);
//gets(str);

//return 0;
//}

//STRING OPERATIONS
//1-LENGTH:
//strlen(s1) returns length of string.

//USING PRE DEFINED FUNCTION


//CODE TO FIND LENGTH OF STRING
//#include<stdio.h>
//int main()
//{
// int length;
// char str[10];
// printf("enter your name");
//gets(str);
//length=strlen(str); //strlen(str)
//printf("length of entered string is :%d",length);
//return 0;
//}

//WITHOUT USING PRE DEFINED FUNCTION

//HERE,we just have to check that when any of character of string='/0'null


character .
//the string will be terminated so here we can check length of string
//#include<stdio.h>
//int main()
//{
// int length;
// char str[10],i;
// printf("enter your name:");
// gets(str);
//while(str[i]!='\0')
// i++;
//length=i;
//printf("length of entered string is :%d",length);
//return 0;
//}

//2-CONVERT STRING TO UPPERCASE


//ASCII CODE FOR A-Z :65 to 90
//ASCII CODE FOR a-z :97 TO 122

//IN ORDER TO convert into uppercase -32


//IN ORDER TO convert into lowercase +32

//strupr():library function used to convert string into uppercase


//strlwr():library function used to convert string into lowercase

//CODE TO CONVERT GIVEN STRING TO UPPERCASE USING PRE DEFINED FUNCTION


//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char str[100];

// printf("enter your name:");


// gets(str);
// strupr(str);
// puts(str);
//return 0;
//}

//CODE TO CONVERT STRING INTO UPPERCASE WITHOUT USING PRE-DEFINED FUNCTION


//#include<stdio.h>
//#include<string.h>

//int main()
//{
// int i;
//char str[50];
// printf("enter your string");
// gets(str);
// while(str[i]!='\0')
//{
// if(str[i]>='a' && str[i]<='z')
//{
// str[i]=str[i]-32;
// i++;

//}

// }
// puts(str);
//return 0;
//}

//CODE TO CONVERT GIVEN STRING TO LOWERCASE USING PRE DEFINED FUNCTION


//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char str[100];
// printf("enter your name:");
// gets(str);
// strlwr(str);
// puts(str);
//return 0;
//}

//CODE TO CONVERT STRING INTO LOWERCASE WITHOUT USING PRE-DEFINED FUNCTION


//#include<stdio.h>
//#include<string.h>

//int main()
//{
// int i;
//char str[50];
//printf("enter your string");
//gets(str);
//while(str[i]!='\0')
//{
// if(str[i]>='A' && str[i]<='Z')
// {
// str[i]=str[i]+32;
// i++;
//}
//}
//puts(str);
//return 0;
//}

//CONCTINATING TWO STRINGS

//strncat() is used to concatinate two strings......

//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char s1[1000],s2[1000];
// int i,j;

// printf("Enter string1: ");


// gets(s1);
// printf("Enter string2: ");
// gets(s2);
// j=strlen(s1);

// for(i=0;s2[i]!='\0';i++)
//{
//s1[i+j]=s2[i];
//}
//s1[i+j]='\0';

//printf("combined two strings ='%s'\n",s1);

//return 0;
//}

//APPENDING TWO STRINGS


//

//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char s1[1000],s2[1000];
// int i,j;
// printf("Enter source string: ");
// gets(s1);
// printf("Enter destination string: ");
// gets(s2);
// while(s2[i]!='\0')
// i++;
// while(s1[i]!='\0')
//{
// s2[i]=s1[i];
// i++;
// j++;
//}
//s2[i]='\0';

//printf("combined two strings ='%s'\n",s2);


//return 0;
//}

//COMPARING TWO STRINGS


//there is a library function strcat(s1,s2) that concatinates s2 with s1....it is
defined in string.h.
//DURING COMPARISON ONE OUT OF 3 CASES CAN OCCUR-
//1-S1=S2
//2-S1>S2
//3-S1<S2

//In order to compare two strings firstly we're required to check length of string

//#include<string.h>
//#include<stdio.h>
//int main()
//{

// char str1[10];
// char str2[10];
// int len1=0,len2=0,i;

// printf("enter string 1");


//gets(str1);
// len1=strlen(str1);
// printf("enter string 2");
// gets(str2);
// len2=strlen(str2);

// if(len1==len2)

// {
// if(str1[i]==str2[i])
// {

// printf("both the strings are equal");

//}
//if(str1[i]!=str2[i])
// {

// printf("strings are not equal");

// }
// }

// if(len1!=len2)
// if(str1[i]!=str2[i])
// printf("strings are not equal");

//}

//REVERSING THE STRING


//IN order to reverse the string we just have to swap first character to
last ....second character to last second character and so on.

//strrev(s1): library function that reverses all the characters in the string
except null character.....it is defined in string.h

//#include<stdio.h>
//#include<string.h>
//int main()
//{
// int i,len1;
// char str[100],temp;
// printf("enter string 1");
// gets(str);
// len1=strlen(str);
// while(i<len1)
// {
// temp=str[i];
// str[i]=str[len1-1];
// str[len1-1]=temp;
// i++;
// len1--;
//}
// printf("the reversed string is :");
// puts(str);
// return 0;
//}

//STRING MANIPULATION FUNCTIONS

//1-strcat: The strcat() function will append a copy of the source string to the
end of destination string. The strcat() function takes two arguments:
//1) dest (DESTINATION STRING)
//2) src (SOURCE STRING)
//It will append copy of the source string in the destination string. The
terminating character at the end of dest is replaced by the first character of
src .
//Return value: The strcat() function returns dest, the pointer to the destination
string.

//#include<stdio.h>
//#include<string.h>
//int main()
//{

// char str1[100],str2[100];
// printf("enter string 1");
// gets(str1);
// printf("enter string 2");
// gets(str2);
// strcat(str1,str2);
// printf("modified string is:%s",str1);

//}

//2-strncat()function
//this function appends the strings pointed to by str2 to the end of the string 1
upto n charcters
//the terminating null charcter of string is overwritten
//#include<stdio.h>
//#include<string.h>
//int main()
//{

// char str1[200];
// char str2[100];
// printf("enter string 1");
// gets(str1);
// printf("enter string 2");
// gets(str2);
// strncat(str1,str2,4);
// printf("modified string is :%s",str1);

//}

//3-strchr()function
//It returns pointer to first occourrence of character
//pointer indicates to position

//#include<stdio.h>
//#include<string.h>
//int main()
//{

// char str[100];
// char ch='b';
// char *ptr;
// printf("enter string:");
// gets(str);
// printf (" Original string is: %s \n", str);
// ptr=strchr(str,'b');
// printf("\n the first occurrence of %c in string is :",ch,ptr,str);
//}

//4-strnchr():this function returns pointer to last occurrence of the character

//5-strcmp():this function compares the string 1 by string 2


//firstly for comparison we should check length of both the strings if equal then
compare else break

//#include<string.h>
//#include<stdio.h>
//int main()
//{
// int len1=0,len2=0;
// char str1[100],str2[100];
// printf("enter string 1 :");
// gets(str1);
// len1=strlen(str1);
// printf("enter string 2 :");
// gets(str2);
// len2=strlen(str2);
// if(strcmp(str1,str2)==0)
// printf("both the strings are equal");
// else
// printf("both the strings are unequal");
//}

//6-strncmp():this function compares at most the first n bytes of str1 and str2.
//the process stops comparing after null character is encountered.
//this function return zero if first n bytes of string are equal

//#include<string.h>
//#include<stdio.h>
//int main()
//{

// int len1=0,len2=0;
// char str1[100],str2[100];
// printf("enter string 1 :");
// gets(str1);
// len1=strlen(str1);
// printf("enter string 2 :");
// gets(str2);
// len2=strlen(str2);
// if(strncmp(str1,str2,2)==0)
// printf("both the strings are equal");
// else
// printf("both the strings are unequal");
//}

//7-strcpy():this function copies string pointed to by str2 to str1 including null


character of str2
//it returns argument str1
//here, str1 should be big enough to store the contents of str2.

//SYNTAX:strcpy(destination string,source string)

//#include<stdio.h>
//#include<string.h>
//int main()
//{

// char str1[100];
// char str2[]="joshi";
// strcpy(str1,str2);
// puts(str1);
//}

//8-strncpy():this function copies upto n charcater from the string pointed to by


str2 to str1.
//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char str1[100];
// char str2[]="joshi";
// strncpy(str1,str2,3);
// puts(str1);
//}

//9-strlen():this function calculates length of the string, doesn't include null


character

//#include<stdio.h>
//#include<string.h>
//int main()
//{

// char str1[100];
// printf("enter string 1");
// gets(str1);
// printf("length of string 1 is :%d",strlen(str1));

//}

//10-strstr():this function is used to find first occurrence of string str2 not


including null character in string str1.
//this function returns pointer to first occurrence of str2 in str1
//if no match is found :RETURNS NULL POINTER

//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char str1[]="happy bith day maa";
// char str2[]="maa";
// char *sub;
// sub=strstr(str1,str2);
// printf("the substring is :%s",sub);

//}

//11-strtok():this function is used to isolate sequential tokens in a null


terminated string .
//these tokens are separated using delimiter

//C provides two functions strtok() and strtok_r() for splitting a string by some
delimiter. Splitting a string is a very common task.
// For example, we have a comma-separated list of items from a file and we want
individual items in an array.
//strtok() Method: Splits str[] according to given delimiters and returns the next
token.
//It needs to be called in a loop to get all tokens. It returns NULL when there are
no more tokens.

//SYNTAX:char * strtok(char str[], const char *delims);

//#include<stdio.h>
//#include<string.h>
//int main()
//{
// char str1[]="happy bith day maa";
// char delim[]=",";

// char *result;
// result=strtok(str1,delim);
// while(result!=NULL);
// {
// printf("%s",result);
// result=strtok(NULL,delim);
// }

// printf("the resultant string is :%s",result);


//}

///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////
///////////////////////////////////////////////////
POINTERS////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////

//Pointers - a variable that stores the memory address of another variable as its
value.

//WHY DO WE USE POINTERS?

//In dynamic memory allocation you request the computer for memory. The compiler
goes and sees what memory it has available.
// Assuming it has enough to give us, the operating system will set aside the
amount of memory requested and give us that memory's address so that we can use it.
// How do we store an address ? In a pointer !! Allocation and de-allocation of
memory can be done easily using functions and thus pointers fit the case here.

//pointers provide handy way to access arrays and strings

//last but not the least ,the most powerful use of pointers is to dynamically
allocate memory for variables

//generally computer has three areas of memory each of which is used for specific
task

//1-STACK: stack is a section of memory that is allocated for automatic variables


within functions
//2-HEAP: it is a contiguous block of memory that is available for use by the
program when need arises

//COMPARED TO HEAP ,A STACK IS FASTER BUT SMALLER AND EXPENSIVE

//3-GLOBAL MEMORY: the block of code that is in main() program is stored in global
memory.
// : the memory in global area is allocated randomly to store the
code of different functions in the program
// in such a way that one function is not
contiguous to other

//Referencing of Pointer (Initialization of Pointer)


//Making a pointer variable to point other variables by providing address of that
variable to the pointer is known as referencing of pointer.

//Examples of Referencing of Pointer:

//int a=5;
//int *ptr;
//ptr = &a;

//Here pointer ptr got address of variable a so, pointer ptr is now pointing to
variable a.

//Dereferencing of Pointer
//So far, the operator * (star) 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;
//int *ptr;
//ptr = &a;
//printf(“a = %d”, *ptr);

//This prints a = 5 which is accessed through pointer.

//DECLARATION OF POINTER VARIABLE


//the data type of pointer variable and the variable to which it points must be
same

//SYNATX: data_type *ptr _name; (here data_type is the type of value that the
pointer will point to)
// (here * informs compiler that ptr is pointer
variable )

//eg:int*a;
// :float *b;
// :char *c;

//int x;
//int *ptr;
//ptr=&x;

//here,ptr is name of pointer variable


//here * informs compiler that ptr is pointer variable
//int specifies that it will store the address of an integer variable
//at last ,ptr is assigned to address of x

//IN C ,pointers are not allowed to store memory address ,but they can store
address of variables of a given type
//therefore,
// int *ptr =1000;is absolutely illegal in c.

//address of memory location is constant ,therefore it cannot be changed in program


code

//NOTE: %p -prints the argument as a memory address in hexadecimal form


// : %u -prints the argument as a memory address in decimal form

// WHAT WILL BE VALUE OF


// *(&num) it will be equal to value of num AS
INDIRECTION AND ADDRESS OPERATORS ARE INVERSE OF EACH OTHER

//any no. of pointer can point to the same address


//the address of variable is the address of first byte occupied by the variable

//#include<stdio.h>
//int main()
//{
// int a=9,b=5;
// int *pnum;
// pnum=&a;
// printf("\n a=%d",*pnum);
// pnum=&b;
// printf("\n b=%d",*pnum);
// return 0;

//}
//PROGRAMMING TIPS
//1-Its an an error to subtract two pointer variables
//2-A pointer variable can be assigned the address of another variable(same data
type)
//3-A pointer variable can be assigned the VALUE of another variable(same data
type)
//4-It can be initialized with NULL VALUE(/0) or ZERO VALUE
//5-WHEN USING POINTERS ,UNARY INCREMENT(++) AND DECREMENT (--)OPERATORS HAVE
GREATER PRECEDENCE THAN DEREFERENCE OPERATOR(*)
//6-AN integer value can be added or subtracted from a pointer variable
//7-A pointer variable can be compared with another pointer variable of same type
using relational operators
//8-A pointer variable can not be multiplied with constant
//9-A pointer variable can not be added to another pointer variable

//FOR EXAMPLE:
//#include<stdio.h>
//int main()
//{
// int n1=1,n2=2,sum=0,mul=0,div=0;
// int *ptr1,ptr2;
// ptr1=&n1;
// ptr2=&n2;

// sum=*ptr1 + 2;
// mul=*ptr1 * 2;
// div=*ptr1 / 2;
// printf("\n sum=%d",sum);
// printf("\n multiplication=%d",mul);
// printf("\n division =%d",div);
// return 0;
//}

//WAP TO PRINT HELLO WORLD USING POINTER


//#include<stdio.h>
//int main()
//{
// char *ch="HELLO WORLD";
// printf("%s",ch);
// return 0;
//}

//WAP TO ADD TWO FLOATING POINT NOS. USING POINTER .THE RESULT SHOULD CONTAIN ONLY
TWO DIGITS AFTER THE DECIMAL.
//#include<stdio.h>
//int main()
//{
// float num1,num2,sum;
// float *ptr1=&num1,*ptr2=&num2;

// printf("enter nos.1 :");


// scanf("%f",&ptr1);
// printf("enter nos.2 :");
// scanf("%f",&ptr2);

// sum=*ptr1 + num2;
// printf("\n sum of two nos. is %f + %f = %.2f",*ptr1,*ptr2,sum);
// return 0;

//}

//WAP TO FIND BIGGEST OF Three NOS. USING POINTERS


//#include<stdio.h>
//int main()
//{
// int num1,num2,num3;
// int *ptr1=&num1,*ptr2=&num2,*ptr3=&num3;

// printf("enter no.1 :");


// scanf("%d",&num1);
// printf("enter no.2 :");
// scanf("%d",&num2);
// printf("enter no.3 :");
// scanf("%d",&num3);
// int *lar=&num1;
// if(*ptr2>*lar && *ptr2>*ptr3)
// printf("largest of three nos. is %d",*ptr2);
// else if(*ptr3>*lar && *ptr3>*ptr2)
// printf("largest of three nos. is %d",*ptr3);
// else
// printf("largest of three nos. is %d",*ptr1);
// return 0;
//}

//WAP TO ENTER A CHARACTER AND THEN DETERMINE WHETHER IT IS VOWEL OR NOT

//#include<stdio.h>
//int main()
//{
// char ch,*ptr=&ch;
// printf("enter a character :");
// scanf("%c",&ch);
// if(*ptr=='a'||*ptr=='e'||*ptr=='i'||*ptr=='o'||*ptr=='u' ||*ptr=='A'||
*ptr=='E'||*ptr=='I'||*ptr=='O'||*ptr=='U')
// printf("%c is vowel",*ptr);
// else
// printf("%c is not a vowel",*ptr);
// return 0;
//}

//WAP USING POINTER VARIABLES TO READ A CHARACTER UNTILL * IS ENTERED .


//IF THE CHARACTER IS IN UPPERCASE ,PRINT IN LOWER CASE AND VICE VERSA .ALSO COUNT
NO. OF CHARACTERS ENTERED
//#include<stdio.h>
//int main()
//{
// char ch,*ptr=&ch;
// int upper=0,lower=0,count=0;
//printf("enter a character :");
//scanf("%c",&ch);
//while(*ptr!='*')
//{
// if('a'<=*ptr<='z')
// {
// *ptr=*ptr-32;
// upper++;
// count++;
// }
//if('A'<=*ptr<='Z')
// {
// *ptr=*ptr+32;
// lower++;
// count++;
// }

// }
// printf("total no. of uppercase characters are :%d",upper);
// printf("total no. of lowercase characters are :%d",lower);
// printf("total no. of entered characters are :%d",count);
//}

//WAP TO PRINT ALL EVEN NO. FROM M TO N


//#include<stdio.h>
//int main()
//{
// int l,*a=&l,i,*b=&i;
// printf("enter initial value:");
// scanf("%d",&i);
// printf("enter final value:");
// scanf("%d",&l);
// for(i=0;*b<=*a;i++)
// {
// if(i%2==0)
// printf("\n %d is even ");
//else
// printf("\n %d is odd ");
// }
//}

///////////////////////////////////////////////////////////////////////////////////
////////////////////////////
////////////////////////////////////TYPES OF
POINTER///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////
//1-NULL POINTER:
// A null pointer has a reserved value that is called a null pointer
constant for indicating that the pointer does not point to any valid object or
function.
// You can use null pointers in the following cases: Initialize
pointers. Represent conditions such as the end of a list of unknown length.
//To declare a null pointer you must use predefined constant
NULL,which is defined in several standard header files <stdio.h>,<stdlib.h> and
<string.h>
//so now using these standarad header files we can write:
// int *ptr=NULL;

//2-GENERIC POINTER:
// A generic pointer is a pointer variable that has void as its data
type.
//the void or the generic pointer ,is a special type of pointer that
can be used to point to variables of any data type.
//SYNTAX:
// void *ptr;
//IN C , since you cannot have variable of type void ,the void pointer
will ,therefore not point to any data type thus,cannot be dereferenced.
//you need to typecast a void pointer(GENERIC POINTER) to another kind
of pointer before using it.
//generic pointers are often used when u want to point to data of
different types at different times .

//PASSING ARGUMENT TO FUNCTION USING POINTERS

//User-defined function
//You can also create functions as per your need. Such functions created by the
user are known as user-defined functions.

//How user-defined function works?


//#include <stdio.h>
//void functionName()
//{
// ... .. ...
// ... .. ...
//}

//int main()
//{
// ... .. ...
// ... .. ...

// functionName();

// ... .. ...
// ... .. ...
//}
//The execution of a C program begins from the main() function.

//When the compiler encounters functionName();, control of the program jumps to

//void functionName()

//NOTE:
//1- while using pointers to pass argument to a function ,the calling
function must pass address of the variable as arguments and the called function
must dereference
//the arguments to use them in the
function body for processing.

//TO USE POINTER FOR PASSING ARGUMENT TO A FUNTION,THE PROGRAMMER MUST DO


THE FOLLOWING:
//1-Declare the function parameter as a
pointer
//2-use the dereferenced pointer in the
function body
//3-pass the addresses as the actual
argument when function is called.

//WAP TO ADD TWO INTEGERS USING POINTERS

//#include<stdio.h>
//int sum(int *a,int*b,int *t);
//int main()
//{
// int num1,num2,total;
// printf("enter no.1 :");
// scanf("%d",&num1);
// printf("enter no.2 :");
// scanf("%d",&num2);
// sum(&num1,&num2,&total);
// printf("total=%d",total);
// return 0;
//}
//int sum(int *a,int*b,int *t)
//{
// *t=*a + *b;
//}

//WAP USING FUNCTIONS TO FIND BIGGEST OF THREE INTEGERS

//#include<stdio.h>
//int big(int *a,int *b,int *c,int*large);
//int main()
//{
// int num1,num2,num3,large=0;
// printf("enter a no.1 :");
// scanf("%d",&num1);
// printf("enter a no.2 :");
// scanf("%d",&num2);
// printf("enter a no.3 :");
// scanf("%d",&num3);
// big(&num1,&num2,&num3,&large);
// printf("large=%d",large);
// return 0;
//}
//int big(int *a,int *b,int *c,int*large)
//{
// if(*a>*b && *a>*c)
// *large=*a;
// if(*b>*a && *b>*c)
// *large=*b;
// if(*c>*a&& *c>*b)
// *large=*c;
//}

//POINTER AND ARRAYS

//example:
//int arr[]={1,2,3,4,5};

//array notation is a form of pointer notation .the name of array is the starting
address of the array in memory .
//it is also known as base address .in other words base address is the address of
first element in the array or the address of arr[0]
//for eg:
//int *ptr;
//ptr=&arr[0];

//here ptr is made to point to the first element of the array.


//execute the code given below and observe the output:

//#include<stdio.h>
//int main()
//{
// int arr[]={1,2,3,4,5};
// printf("\n Address of array = %p%p%p",&arr,&arr[0],&arr);//In C we have seen
different format specifiers. Here we will see another format specifier called %p.
// This
is used to print the pointer type data.
//}

//IF THE POINTER VARIABLE ptr HOLDS THE ADDRESS OF THE FIRST ELEMENT IN THE
ARRAY ,THEN THE ADDRESS OF SUCCESSIVE ELEMENTS CAN BE CALCULATED BY WRITING ptr++
//#include<stdio.h>
//int main()
//{
// int arr[]={1,2,3,4,5};
// int *ptr=&arr[0];
// ptr++;
// printf("\n the value of the second element of the array is %d",*ptr);
//}

//NOTE:
//if x is an integer variable ,then x++,adds 1 to the value of x.
//but ptr is a pointer variable ,
//so when we write ptr+i,then adding i
gives a pointer that points i elements further along an array than the original
pointer.
//LOOK AT THE CODE AND TRY TO UNDERSTAND THE RESULT:
//#include<stdio.h>
//int main()
//{
// int arr[]={1,2,3,4,5};
// int *ptr,i;
// ptr=&arr[2];
// *ptr=-1;
// *(ptr+1)=0;
// *(ptr-1)=1;
// printf("\n Array is :");
// for(i=0;i<5;i++)
// printf("%d",*(arr+i));
//}

//WAP TO READ AND DISPLAY AN ARRAY OF N INTEGERS

//#include<stdio.h>
//main()
//{
//int a[5]={5,4,6,8,9};
//int *p=&a[0];
//int i;
//for(i=0;i<5;i++)
//printf("%d ",*(p+i));

//}

//WAP TO FIND MEAN OF N NUMBERS USING ARRAY


//#include<stdio.h>
//int main()
//{
// int n,*pn=&n,sum=0,mean=0, arr[20],*ptr=&arr,i,*s=&sum,*m=&mean;
// #include<stdio.h>
// int main()
// {
// int a[5]={5,4,6,8,9};
// int *ptr=&a[0];
// int i;
// for(i=0;i<5;i++)
// printf("%d ",*(ptr+i));
// }
// for(i=0;i<*pn;i++)
// {
// *s+=*(arr+i);
// *m=*s/ *pn;
// printf("no. u entered are: ");
// }
// for(i=0;i<*pn;i++)
// printf("%d",*(arr+i));
//printf("\n mean is :%f",*m);
//return 0;
//}
//////POINTER AND STRINGS//////

//In C,strings are treated as array of characters that are terminated with a binary
zero character (written as '\0')
//consider one example here:
//char str[10];
//str[0]='H';
//str[1]='i';
//str[2]='i';
//str[3]='\0';

//C LANGUAGE PROVIDES TWO ALTERNATIVE WAYS OF DECLARING AND INITIALISING STRING:

//1- char str ={'H','I','I','\0'};

//2- char str[10]="hii!";


//when the double quotes are used ,null character is
automatically appended to the end of string.

//WAP TO READ AND PRINT A TEXT .ALSO COUNT THE NUMBER OF CHARCTERS ,WORDS ,AND
LINES IN THE TEXT.
//#include<stdio.h>
//int main()
//{
// char str[100],*ptr=&str;
// int ccount=0,lcount=0,wcount=0;
// printf("enter a string :");
// gets(str);
// ptr=str;
// while(*ptr!='\0')
// {
// if(*ptr=='\n')
// lcount++;
//
// else if(*ptr=' ')
// wcount++;
//
// else (*ptr!=' ' && '\n');
// ccount++;
// }
// printf("the string is %s");
// gets(str);
// printf("no. of lines :%d",lcount);
// printf("no. of words :%d",wcount);
// printf("no. of characters :%d",ccount);
// return 0;
//}

//WAP TO READ A TEXT ,DELETE ALL THE SEMI COLANS IT HAS,AND FINALLY REPLACE ALL
'.' WITH A ','
//#include<stdio.h>
//int main()
//{
// char string[100],*ptr=&string;
// printf("enter a string");
// gets(string);
// string=string.replace(";","");
// gets(string);

//}

//////////////////////POINTER TO POINTER //////////////////////////

//in c language you are allowed to use pointers that point to pointers .the
pointers in turn ,point to data (or to other pointer )
//to declare pointer to pointers ,just add an (*)asterisk for each level of
reference .

//#include<stdio.h>
//int main()
//{
// int x=40,*px,**ppx;
// px=&x;
// ppx=&px;
// printf("%d",**ppx);
//}

///////////////////////MEMORY ALLOCATION AND DE-ALLOCATION/////////////////


//MALLOC:allocates memory and returns a pointer to the first byte of allocated
space
//

You might also like