ICS - Lecture
य आपको अं जी के कारण कोई सम आ रही है तो हमसे संप करने संकोच न क
Slides are prepared from various sources on the web.
दि
ग्रे
स्या
र्क
में
रें
Arrays
Array
An array is defined as the collection of similar type (float/int/char/…)
of data items stored at contiguous memory locations.
Tell me the output
Int main()
{
float a[4] = {10.3, 21, 4 , 0}; // declaring and initializing an array
a[2] = 18;
printf ("%f\n", a[0]);
printf ("%f\n", a[1]);
printf ("%f\n", a[2]);
printf ("%f\n", a[3]);
}
Array
What if we try to store more
Elements than 4?
Int main()
In GCC, warning with garbage.
{
Output may change based on
int a[4] = {10, 21, 4 , 0, 17}; // declaring and initializing an
Compilers.
array
C does not give error, so be careful.
Array bounds are not checked.
a[2] = 18;
printf ("%d\n", a[0]);
printf ("%d\n", a[1]);
printf ("%d\n", a[2]);
printf ("%d\n", a[3]);
}
Tell me the output
Int main()
{
float a[4] = {10.3, 21, 4 , 0}; // declaring and initializing an array
a[7] = 18;
printf ("%f\n", a[0]);
printf ("%f\n", a[1]);
printf ("%f\n", a[2]);
printf ("%f\n", a[3]);
}
Tell me the output
Int main()
{
float a[4] = {10.3, 21, 4 , 0}; // declaring and initializing an array 10.300000
a[7] = 18; 21.000000
4.000000
printf ("%f\n", a[0]); 0.000000
printf ("%f\n", a[1]); Segmentation fault
printf ("%f\n", a[2]);
printf ("%f\n", a[3]);
}
Segmentation Fault
• A Segmentation Fault in C, also known as a segfault, is an error that
occurs when a program tries to access memory that it is not allowed
to access. In C programming language, a Segmentation Fault in C
occurs when a program attempts to read or write to a memory
location that has not been allocated to it.
2D array
Sum of matrices 1
Input by the user:
• No of Rows
• No of Cols
• Enter each element in 1st Matrix
• Enter each element in 2nd Matrix
2
Sum of matrices 1
Input by the user:
• No of Rows
• No of Cols
• Enter each element in 1st Matrix
• Enter each element in 2nd Matrix
Sum
Sum of matrices 1
Input by the user:
• No of Rows
• No of Cols
• Enter each element in 1st Matrix
• Enter each element in 2nd Matrix
Sum
2
Sum of matrices 1
Input by the user:
• No of Rows
• No of Cols
• Enter each element in 1st Matrix
• Enter each element in 2nd Matrix
Sum
2 4
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
Sum of matrices printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
Input by the user: for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
• No of Rows
scanf("%d", &a[i][j]);
• No of Cols }
• Enter each element in 1st Matrix printf("Enter elements of 2nd matrix:\n");
• Enter each element in 2nd Matrix for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n"); }}}
Practice Questions
• count negative elements in array
•
#define MAX_SIZE 100 // Maximum array size
int main()
Practice Questions {
int arr[MAX_SIZE]; // Declares array of size 100
int i, size, count = 0;
/* Input size of array */
• count negative elements in printf("Enter size of the array : ");
scanf("%d", &size);
array /* Input array elements */
printf("Enter elements in array : ");
• What did we see here for(i=0; i<size; i++)
{
(something new)? }
scanf("%d", &arr[i]);
/* Count total negative elements in array*/
for(i=0; i<size; i++)
{
/* Increment count if current array element is negative */
if(arr[i] < 0)
{
count++;
}
}
printf("\nTotal negative elements in array = %d", count);
return 0;
}
Macros #include <stdio.h>
• In C programming, #define is a preprocessor directive that is // Defining parameterized macros with expression
used to define macros. The macros are the identifiers defined #define CIRCLE_AREA(r) (3.14 * r * r)
by #define which are replaced by their value before compilation #define SQUARE_AREA(s) (s * s)
• #define MACRO_NAME value int main()
• #define MACRO_NAME (expression within brackets) {
• #define MACRO_NAME(ARG1, ARG2,..) (expression within int radius = 21;
brackets) int side = 5;
int area;
// Using macros to calculate areas by passing argument
#include <stdio.h> area = CIRCLE_AREA(radius);
#define PI 3.14159265359 printf("Area of Circle of radius %d: %d \n", radius,
int main() area);
{
int radius = 21; area = SQUARE_AREA(side);
int area; printf("Area of square of side %d: %d", side, area);
area = PI * radius * radius;
printf("Area of Circle of radius %d: %d", radius, area); return 0;
return 0; }
}
C program to insert an element in array
• Input array elements: 10, 20, 30, 40, 50
• Input element to insert: 25
• Input position where to insert: 3
• Elements of array are: 10, 20, 25, 30, 40, 50
/**
* C program to insert an element in array at specified position /* If position of element is not valid */
*/ if(pos > size+1 || pos <= 0)
{
#include <stdio.h> printf("Invalid position! Please enter position between 1 to %d", size);
#define MAX_SIZE 100 }
else
int main() {
{ /* Make room for new array element by shifting to right */
int arr[MAX_SIZE]; for(i=size; i>=pos; i--)
int i, size, num, pos; {
arr[i] = arr[i-1];
/* Input size of the array */ }
printf("Enter size of the array : ");
scanf("%d", &size); /* Insert new element at given position and increment size */
arr[pos-1] = num;
/* Input elements in array */ size++;
printf("Enter elements in array : ");
for(i=0; i<size; i++) /* Print array after insert operation */
{ printf("Array elements after insertion : ");
scanf("%d", &arr[i]); for(i=0; i<size; i++)
} {
printf("%d\t", arr[i]);
/* Input new element and position to insert */ }
printf("Enter element to insert : "); }
scanf("%d", &num);
printf("Enter the element position : "); return 0;
scanf("%d", &pos); }
/**
* C program to insert an element in array at specified position /* If position of element is not valid */
*/ if(pos > size+1 || pos <= 0)
{
#include <stdio.h> printf("Invalid position! Please enter position between 1 to %d", size);
#define MAX_SIZE 100 }
else
int main() {
{ /* Make room for new array element by shifting to right */
int arr[MAX_SIZE]; for(i=size; i>=pos; i--)
int i, size, num, pos; {
arr[i] = arr[i-1];
/* Input size of the array */ }
printf("Enter size of the array : ");
scanf("%d", &size); /* Insert new element at given position and increment size */
What is the limitation here? arr[pos-1] = num;
/* Input elements in array */ size++;
printf("Enter elements in array : ");
for(i=0; i<size; i++) /* Print array after insert operation */
{ printf("Array elements after insertion : ");
scanf("%d", &arr[i]); for(i=0; i<size; i++)
} {
printf("%d\t", arr[i]);
/* Input new element and position to insert */ }
printf("Enter element to insert : "); }
scanf("%d", &num);
printf("Enter the element position : "); return 0;
scanf("%d", &pos); }
For a matrix, compute transpose
int main() { // computing the transpose
int a[10][10], transpose[10][10], r, c; for (int i = 0; i < r; ++i)
printf("Enter rows and columns: "); for (int j = 0; j < c; ++j) {
scanf("%d %d", &r, &c); transpose[j][i] = a[i][j];
}
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n"); // printing the transpose
for (int i = 0; i < r; ++i) printf("\nTranspose of the matrix:\n");
for (int j = 0; j < c; ++j) { for (int i = 0; i < c; ++i)
printf("Enter element a%d%d: ", i + 1, j + 1); for (int j = 0; j < r; ++j) {
scanf("%d", &a[i][j]); printf("%d ", transpose[i][j]);
} if (j == r - 1)
printf("\n");
// printing the matrix a[][] }
printf("\nEntered matrix: \n"); return 0;
for (int i = 0; i < r; ++i) }
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
Do it yourself Program
• Write a C program to read elements in a matrix and interchange elements of
primary(major) diagonal with secondary(minor) diagonal.
Input matrix elements:
123
456
789
Matrix after interchanging its diagonal:
321
456
987
What is the idea here?
What is the idea here?
/* Interchange diagonal of the matrix*/
for(row=0; row<size; row++)
/*C program to interchange diagonals of a matrix */ {
col = row;
#include <stdio.h>
#define MAX_ROWS 3 temp = A[row][col];
#define MAX_COLS 3 A[row][col] = A[row][(size-col) - 1];
A[row][(size-col) - 1] = temp;
int main() }
{
int A[MAX_ROWS][MAX_COLS]; /* Print the interchanged diagonals matrix*/
int row, col, size, temp; printf("\nMatrix after diagonals interchanged: \n");
for(row=0; row<MAX_ROWS; row++)
/* Input elements in matrix from user */ {
printf("Enter elements in matrix of size %dx%d: \n", MAX_ROWS, MAX_COLS); for(col=0; col<MAX_COLS; col++)
for(row=0; row<MAX_ROWS; row++) {
{ printf("%d ", A[row][col]);
for(col=0; col<MAX_COLS; col++) }
{
scanf("%d", &A[row][col]); printf("\n");
} }
}
size = (MAX_ROWS < MAX_COLS) ? MAX_ROWS : MAX_COLS; return 0;
}
Do it yourself - delete duplicate elements
from array
• Input array elements: 12, 44, 21, 44, 11, 54, 12, 50, 54, 100
• Elements of array are: 12, 44, 21, 11, 54, 50, 100
• What is the logic?
more practice
• C program to check sparse matrix
• What is sparse matrix?
• What is the concept?
Find the largest number in an array
START
Step 1 → Take an array A and de ne its values
Step 2 → Declare largest as integer
Step 3 → Set 'largest' to 0
Step 4 → Loop for each value of A
Step 5 → If A[n] > largest, Assign A[n] to largest
Step 6 → After loop nishes, Display largest as largest element of array
STOP
fi
fi
C Code
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int loop, largest;
largest = array[0];
for(loop = 1; loop < 10; loop++) {
if( largest < array[loop] )
largest = array[loop];
}
printf("Largest element of array is %d", largest);
return 0;
}
•
Sorting arrays
How you would sort n-elements?
• Different methods
• We will discuss one here
This is called bubble sort
Key idea
1.for (i = 0; i < n - 1; i++) {
2. for (j = 0; j < n - i - 1; j++) {
3. if (arr[j] > arr[j + 1]) {
4. int temp = arr[j];
5. arr[j] = arr[j + 1];
6. arr[j + 1] = temp;
7. }
8. }
9. }
10.
3D Array
Multidimensional arrays
Character array
int main()
{
char a[5];
int i;
a[0] = 'H';
a[1] = 'E';
a[2] = 'L';
a[3] = 'L';
a[4] = 'O';
for (i = 0; i < 5; ++i)
{
printf("%c", a[i]);
}
return 0;
}
39
No string data type is directly available
int main()
{
char a[5];
int i;
a[0] = 'H';
a[1] = 'E';
a[2] = 'L';
a[3] = 'L';
a[4] = 'O';
special null character, denoted by '\0' a[5] = '\0'; //This should be explicitly inserted to treat it like a string
for (i = 0; i < 5; ++i)
{
printf("%c", a[i]);
}
printf("\n%c",a[i]);
printf("\n%s", a);
return 0;
}
40
int main()
{
char a[6]="hello"; // make it 6 for safe side.
char b[] = "Welcome IITJ students"; // This is also possible
printf("%s\n", a);
printf("%s\n", b);
return 0;
}
41
Output?
int main()
{
char b[] = “This is ICS course";
int count = 0,i = 0;
while (b[i] != '\0') What is this this?
{
if(b[i] == 'S' || b[i] == 's')
count++;
i++;
}
printf("count: %d\n", count);
return 0;
}
String library <string.h> int main()
{
char b[] = "Welcome IITJ Students";
char a[50], c[50];
int count = 0,i = 0;
count = strlen(b);
printf("The length is : %d\n", count);
for (i = 0; i < count; ++i)
{
a[i] = b[i];
}
a[i] = '\0';
strcpy(c, b); // (des, src);
if(strcmp(a, c) == 0)
printf("Both same\n");
return 0;
}