UNIT III C Final
UNIT III C Final
1.ARRAYS INDEXING
Definition:
An array is a variable that can store multiple values. An array is defined as finite ordered collection of
homogenous data, stored in contiguous memory locations. Here the words,
finite means data range must be defined.
ordered means data must be stored in continuous memory addresses.
homogenous means data must be of similar data type.
Syntax / Declaring arrays
dataType arrayName[arraySize];
Data_type: It will decide the type of elements the array will accept. For example, If we want to store
integers, then we declare the Data Type as int. If we want to store floating-point values, then we declare
the Data Type as float, etc
ArrName: This is the name you want to give to it. For example, students, age, marks, employees, etc
Arr_Size: Number of elements an array can hold or store. For example, if Arr_Size =10, it will hold
10 values.
Example
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-
point values.
It's important to note that the size and type of an array cannot be changed once it is declared.
Initialization of Array in C
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value).
An array can be initialized at either compile time or at runtime. That means, either we can provide values to
the array in the code itself, or we can add user input value into the array.
Compile time Array initialization in C
Compile time initialization of array means we provide the value for the array in the code, when we create the
array,
data-type array-name[size] = { list of values };
For example: int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5
elements.
#include<stdio.h> Output
void main()
{ 2 3 4
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
return 0;
}
2.MEMORY MODEL
When we execute a C program, the executable code of the file loads into RAM in an organized manner.
Computers do not access program instructions directly from secondary storage because the access time of
secondary storage is longer when compared to that of RAM. RAM is faster than secondary storage but has a
limited storage capacity, so it is necessary for programmers to utilize this limited storage efficiently.
Knowledge of memory layout in C is helpful to programmers because they can decide the amount of memory
utilized by the program for its execution.
C program memory layout in C mainly comprises six components these are heap, stack, code segment,
command-line arguments, uninitialized and initialized data segments.
Diagram for memory structure of C
The diagram mentioned below shows a visual representation of how RAM loads a program written in C into
several segments.
Code segment
The code segment, also known as the text segment, is where the compiled machine instructions of the program
are stored. It contains the executable code, including functions, statements, and instructions that make up the
program's logic. This segment is typically read-only and shared among multiple instances of the same program.
Data Segment:
The data which we use in our program will be stored in data section.
Since the variables declared inside the main () function are stored in the stack, but the variables declared
outside the main () method will be stored in data section.
The variables declared in the data section could be stored in the form of initialized, uninitialized, and
it could be global or local.
Therefore, the data section is divided into four categories i.e., initialized, uninitialized, global or local.
Example
int var1; Here var1 and var2 variables are declared outside the main()
int var2=10; function where var1 is the uninitialized variable, whereas the
void function1() var2 is an initialized variable.
{ These variables can be accessed anywhere in the program
printf(“i am function1”); Because these variables are not a part of the main() in the stack.
}
int main()
{
function1();
return 0;
}
The data segment is divided into two segments:
1. Uninitialized Data Segment
The uninitialized data segment is also known as a .bss segment that stores all the uninitialized global, local
and extern variables. The .bss segment stands for Block Started by a symbol.
char a; // uninitialized global variable.
int main()
{
static int a; // uninitialized static variable.
return 0;
}
2. Initialized data segment
An initialized data segment is also known as the data segment. A data segment is a virtual address space of a
program that contains all the global and static variables which are explicitly initialized by the programmer.
char string[]=”memory”; // global variable stored in initialized data segment in read-write area
int main()
{
static int i=90; // static variable stored in initialized data segment
return 0;
}
Stack
The stack area traditionally adjoined the heap area and grew in the opposite direction; when the stack
pointer met the heap pointer, free memory was exhausted.
When we define a function and call that function then we use the stack frame.
The stack section plays a very important role in the memory because whenever the function is called,
a new stack frame is created.
Stack is also used for recursive functions.
Heap
Heap memory is used for the dynamic memory allocation.
Heap memory begins from the end of uninitialized data segment and grows upwards to the higher
addresses.
The malloc() and calloc() functions are used to allocate the memory in the heap.
The heap memory can be used by all the shared libraries and dynamically loaded modules.
The free() function is used to deallocate the memory from the heap.
void main()
{
int arr1[100], arr2[100];
int i, n;
printf("\n\nCopy the elements one array into another array :\n");
printf("----------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/* Copy elements of first array into second array.*/
for(i=0; i<n; i++)
{
arr2[i] = arr1[i];
}
Initialization of 2D Array in C
We can initialize the 2D array in c by using two methods.
Using Initializer List
Using Loops
Initializing using Initializer List
In the initializer list we have two methods to declare the two dimensional array in C.
First Method
In the first method we can write all the elements together.
int a[4][3] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Here the array contains 4 rows and 3 columns. We read the elements in the matrix from left to right so in this
also the elements are read from left to right so after every 3 elements we go to the new row, and the new row
starts to be filled.
Second Method
This method is comparatively better as we have clearly specified the elements in each row.
int a[4][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}};
In the above example we have nested brackets which shows the element of each row individually.
Accessing elements in two-dimensional arrays
Just like one-dimensional arrays, two-dimensional arrays also require indices to access the required elements.
A row and a column index are needed to access a particular element; for nested loops, two indices (one to
traverse the rows and the other to traverse the columns in each row) are required to print a two-dimensional
array.
array_name[x][y]
Where;
x: is the row index.
y: is the column index
Looping Through a 2D Array
#include <stdio.h> Output
int main() { 123
int grid[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}}; 456
// Loop through the 2D array and print its elements 789
for (int i = 0; i < 3; i++) { // Iterate over rows
for (int j = 0; j < 3; j++) { // Iterate over columns
printf("%d ", grid[i][j]); // Print the current element
}
printf("\n"); // Move to the next row
}
return 0;
}
Example 1: Matrix addition in c
To perform matrix addition in C programming, we can use multi-dimensional arrays. A multi-dimensional
array is an array that can store an array within an array, allowing us to represent matrices. For instance, a two-
dimensional array with int matrix[row][column] can store a matrix with the specified number of rows and
columns.
#include <stdio.h> Output
return 0;
}
void main()
{
int arr1[50][50],brr1[50][50],i,j,r,c;
printf("\n\nTranspose of a Matrix :\n");
printf("---------------------------\n"); Transpose of a Matrix :
---------------------------
printf("\nInput the rows and columns of the matrix : "); Input the rows and columns of the matrix : 2 2
scanf("%d %d",&r,&c); Input elements in the first matrix :
element - [0],[0] : 1
printf("Input elements in the first matrix :\n"); element - [0],[1] : 2
for(i=0;i<r;i++) element - [1],[0] : 3
{ element - [1],[1] : 4
for(j=0;j<c;j++)
{ The matrix is :
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]); 1 2
} 3 4
}
The transpose of a matrix is :
printf("\nThe matrix is :\n"); 1 3
for(i=0;i<r;i++) 2 4
{
printf("\n");
for(j=0;j<c;j++)
printf("%d\t",arr1[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
5. INTRODUCTION TO STRINGS
In C programming, a string is a sequence of characters terminated with a null character \0.
For example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a
null character \0 at the end by default.
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];
In the above syntax string_name is any name given to the string variable and size is used to define the length
of the string, i.e the number of characters strings will store.
C String Initialization
A string in C can be initialized in different ways. 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 c[] = "abcd";
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 c[50] = "abcd";
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 c[5] = {'a', 'b', 'c', 'd', '\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 c[] = {'a', 'b', 'c', 'd', '\0'};
int main()
{
// declare and initialize string
char str[] = "vignan";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
String Handling Functions:
C language supports a large number of string handling functions that can be used to carry out many of the
string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h
header file in your programs to use these functions. The following are the most commonly used string handling
functions.
strcat() function in C
It is used to concatenate(combine) two strings.
Syntax: strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
#include <stdio.h> Output
#include <string.h>
int main() { Output string after concatenation: HelloWorld
char string1[10] = "Hello";
char string2[10] = "World";
strcat(string1, string2);
printf("Output string after concatenation: %s", string1);
return 0;
}
strlen() function in c
It is used to show the length of a string.
#include <stdio.h> Output
#include <string.h>
int main() { Length of string string1: 7
char string1[20] = "strings";
printf("Length of string string1: %ld", strlen(string1));
return 0;
}
strcpy() function in c
Copies one string into another. It copies the second string argument to the first string argument.
#include <stdio.h> Output
#include <string.h> String s1 is: I'll be copied to string 1.
int main() {
}
strcmp() function in c
strcmp() takes two strings as input, then compares them, and returns an integer based on the following
condition:
Expression Returns
string 1 > string 2 Positive integer
string 1 < string 2 Negative
string 1 = string 2 Zero
strrev() function in c
It is used to show the reverse of a string.
#include <stdio.h> Output
Enter your string: vignan
int main() Your reverse string is: nangiv
{
char s1[50];