Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views59 pages

After CT1 Pps

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 59

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY

Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : II
Session title: Introduction to Arrays -One Dimensional (1D) Array
Declaration and initialization - Accessing, Indexing and operations
with 1D Arrays -Array Programs – 1D
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using various forms of 1D dimensional array, Declaration and initialization,
Accessing, indexing and operation
ii)Demonstrate the differences and appropriate use cases for indexing and operation with 1D array

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
ARRAY

• An array is defined as an ordered set of similar data items.


• The data items of an array are stored in consecutive memory location in RAM.
Contiguous Memory Allocation
• Theelements of an array are of same data type and each item can accessed using the same
Name.
• Purpose to store multiple values in single variable, which can be accessed using indices.

Declaration OF AN ARRAY
• Size of array has to be specified
• The array informs the compiler to allocate and reserve the specified memory location.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
One Dimensional (1D):
Types of arrays
• Linear arrays

Two Dimensional (2D):


• Matrix form

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
One Dimensional Array
• 1D array is used to represent and store data in a linear
form.
• Array having only one subscript variable is One
Dimensional array

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
Array Declaration
While Declaring a one Dimensional array in C, the data type can be of any type, and
also, give any name to the array, just like naming a random variable.
Syntax:
datatype arrayname[arraysize];

int arr[5]; //arr is the array name of type integer and 5 is


the size of the array

The datatype can be any valid C data type, the arrayName is the name of the array, and the arraySize
is an integer constant.

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
Initialization of 1D Array
• Static Initialization
• Initializing the array at the time of declaration. Array within square
<data_type> <arr_name> [arr_size]={value1, .
brackets if we initialize
value2, value3,…}; array element explicitly
within the list at the time
int numbers[5]= {10,20,30,40,50}; of declaration
Example:
Link: https://tinyurl.com/2zpf3ef7

Link : https://tinyurl.com/4nbvkf94

Default initialization: If not explicitly initialized, array may contain garbage values
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
Accessing Element In 1D Arrays
• The element are accessed by specifying the array name and the index value within the square
brackets.
• Array indexing starts from 0 and end with size -1.
• Try access array element out of the range, the compiler with not show any error message, rather,
it will return some garbage value
Syntax
Link:
<arr_name>[index]; https://tinyurl.com/4waa3sxb
Example
int nums[5] = {0, 1, 2, 3, 4};
printf("%d", nums[0]); //Array element at index 0 is printed
printf("%d", nums[-1]); //Garbage value will be printed

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
Operation with 1D Array

• Traversing : Visiting each element of the array


• Insertion: Adding elements at specific position
• Deletion: Removing elements from specific position
• Updating: changing the value of elements.
numbers[2]= 35; //update the third elements to 35

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
C Program to illustrate declaration, initialization, and accessing of
elements of a one-dimensional array in C
#include <stdio.h>

int main() {

Guess // Declaring and initializing a one-dimensional array


int arr[3] = {10, 20, 30};

the // Alternative way to initialize the array


// arr[0] = 10; arr[1] = 20; arr[2] = 30;

output // Loop to access and print the elements of the array


for (int i = 0; i < 3; i++) {


// Accessing elements of the array
printf(" Value of arr[%d]: %d\n", i, arr[i]);
}

return 0; // End of the program


}
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
#include <stdio.h>

int main() {
int arr[5]; // Declare a 1D array of size 5
int out = 0;
int i;

Guess
printf("Enter 5 integers:\n"); // Prompt the user to enter 5 integers

the for (i = 0; i < 5; i++) {


printf("Enter value for element %d: ", i + 1);
scanf("%d", &arr[i]);

output… }
out += arr[i];

// Print the sum of the array elements


printf("\nThe sum of the array elements is: %d\n", out);

return 0; // End of the program


}
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
#include <stdio.h>

int main() {
// Declare and initialize a 1-D array of size 10
int arr[10] = {34, 7, 1, 32, 5, 62, 78, 8, 45, 12}; // Example values
int i;
int largest, smallest; // Variables to hold the largest and smallest values

// Display the original array


printf("Original array:\n");
for (i = 0; i < 10; i++) { printf("\n\nArray after swapping largest and smallest

Guess
printf("%d ", arr[i]); elements:\n");
}
for (i = 0; i < 10; i++) {
// Initialize largest and smallest
printf("%d ", arr[i]);
}

the
largest = arr[0];
smallest = arr[0];
printf("\n"); // New line for better readability
// Find the largest and smallest elements return 0; // End of the program
for (i = 1; i < 10; i++) { }

output…
if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}

// Swap the largest and smallest elements in the array


for (i = 0; i < 10; i++) {
if (arr[i] == largest) {
arr[i] = smallest; // Replace largest with smallest
} else if (arr[i] == smallest) {
arr[i] = largest; // Replace smallest with largest
}
21CSS101J
} PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
printf("Enter 10 integers:\n");
for (i = 0; i < 10; i++) { #include <stdio.h>

Guess
printf("Element %d: ", i + 1);
int main() {
scanf("%d", &arr[i]); // Read user input into the array int arr[10];
} int evenSum = 0, oddSum = 0;

the
int evenProduct = 1, oddProduct = 1;
// Calculate the sum and product of odd and even elements int i;
for (i = 0; i < 10; i++) {
if (arr[i] % 2 == 0) { // Check if the element is even

output…
evenSum += arr[i];
evenProduct *= arr[i];
} else { // If the element is odd
oddSum += arr[i];
oddProduct *= arr[i];
}
}

odd even // Display the results

sum
printf("\nSum of even elements: %d\n", evenSum);
printf("Product of even elements: %d\n", evenProduct);
printf("Sum of odd elements: %d\n", oddSum);
printf("Product of odd elements: %d\n", oddProduct);

return 0; // End of the program


}
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
#include <stdio.h>

int main() {
// Declare and initialize a 1-D array of size 10
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // You can change these values as needed
int i;

Guess // Display the original array


printf("Original array:\n");
for (i = 0; i < 10; i++) {

the }
printf("%d ", arr[i]);

output… // Display the array in reverse order


printf("\n\nArray in reverse order:\n");
for (i = 9; i >= 0; i--) {

reverse }
printf("%d ", arr[i]);

printf("\n"); // New line for better readability


return 0; // End of the program
}

21CSS101J PROGRAMMING FOR PROBLEM SOLVING


07-08-2024
- UNIT II
Coding Assignments
1. Write a C program to determine the sum and product of odd and
even elements of a 1-D array of size 10. Display the sum and
product
2. Write a C program to declare a 1-D array of size 10. Initialize the
array and display them. Display the array in reverse order.
3. Initialize the array and the swap the largest and smallest
element of the array. Display the array. Display the array before
and after swapping.
4. To determine the largest and smallest element of a 1 D array of
size 10.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING
07-08-2024
- UNIT II
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : II
Session title: Two dimensional (2D) arrays in C
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using various forms of initializing and accessing 2D arrays and 2D pointers.
ii)Demonstrate appropriate use cases for 2D arrays.

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


2D array

• The two dimensional (2D) array in C programming is also known as matrix. A


matrix can be represented as a table of rows and columns.

• Two-dimensional arrays or multi-dimensional arrays are arrays where the data


element's position is referred to, by two indices.

Need For Two-Dimensional Arrays

Using 2d arrays, you can store so much data at one moment, which can be passed at
any number of functions whenever required.
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Example
• A class consists of 4 students, and the class has to publish the result of all those
students. You need a table to store all those four students' names, subjects' names,
and marks. For that, it requires storing all information in a tabular form
comprising rows and columns. A row contains the name of subjects, and columns
contain the name of the students. That class consists of four subjects, namely
English, Science, Mathematics, and Hindi, and the names of the students are first,
second, third, fourth.

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


Declaration of Two-Dimensional
Arrays
The syntax of two-dimensional arrays is:
Data_type name_of the array[rows][index];
Example:
int multi_dim[2][3];

In the above example, the name of the 2d array is multi_dim consisting of 2 rows and
three columns of integer data types.
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
2D Array Conceptual Memory
Representation
• Example: The abc array with dimension of 5*4

The array has first subscript value as 5 and second subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Actual Memory representation of array

• The actual memory locations are represented by hex.


• Here for better understanding it is represented by integer to show the
contiguos location
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Initialization of Two-Dimensional
Arrays
There are two methods to initialize two-dimensional arrays.
Method 1
int multi_dim[4][3]={10,20,30,40,50,60,20,80,90,100,110,120};

Method 2
int multi_dim[4][3]={{10,20,30},{40,50,60},{70,80,90},{100,110,120}};

*second method is more readable and understandable so that you can


clearly visualize that multi_dim 2D arrays comprise four rows and three
columns.
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Accessing Two-Dimensional Arrays
• Accessing two-dimensional arrays can be done using row index value and column
index value.
Name_of_the arrays[row_index][column_index];
Int multi_dim[4][3]={{10,20,30},{40,50,60},{70,80,90},{100,110,120}};
Accessing the element 80 by row index value and column index value.
Multi_dim[2][1];

Note: indexing always starts with zero


11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Printing the Elements in a Two-
Dimensional Array
Printing elements of a two-dimensional array can be done using two for
loops.
Example 1: https://tinyurl.com/28xvue5n

Example 2: https://tinyurl.com/3ecs3jmb

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


2D POINTERS
How 2D Arrays are Stored in Memory

• In memory, 2D arrays are stored in row-major order.


• This means that the elements of each row are stored in consecutive memory locations before moving to the
next row.
• Understanding this layout is crucial for effectively navigating a 2D array with pointers, as it affects how we
calculate the address of each element.

Basic Syntax for Declaring 2D Arrays


The syntax for declaring a 2D array in C is as follows:
datatype arrayName[rowSize][columnSize];

For example, to declare a 2D array of integers with 3 rows and 5 columns, you would write:
int matrix[3][5];
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Accessing Elements in a 2D Array Using
Pointers
Direct vs Indirect Element Access

• Direct element access involves using the array subscript notation (array[i][j]) to
directly access an element.
• Indirect access, on the other hand, involves calculating the address of the element
using pointer arithmetic and then dereferencing it.
• Example: Accessing the element at the first row and second column of a 2D array
named matrix can be done directly with matrix[0][1] or indirectly with *(*(matrix
+ 0) + 1).

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


Address Operator & in C
• The Address Operator in C is a special unary operator that returns the address of a
variable.
• It is denoted as the Ampersand Symbol ( & ).
• This operator returns an integer value which is the address of its operand in the memory.
• The address operator (&) with any kind of variables, array, strings, functions, and even
pointers.
Syntax
The address operator is generally used as a prefix to its operand:
&operand
where operand can be a variable, array, function, pointer, etc.

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


C program to illustrate the use of address
operator
Example: https://tinyurl.com/5n93e78t
A variable x was defined and initialized with the value 100 in the program above.
We retrieved the address of this variable x by using the address operator (&) as the
prefix and printed it using printf() function.
Note: The %p format specifier to print the address in hexadecimal form.
Generally, the value returned by the address operator is stored in the pointer variable
and then the pointer is dereferenced to get the value stored in that address.
Using a pointer to store the address returned by the address operator and then
dereferencing it
Example: https://tinyurl.com/3fzfpcea

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


Address Operator Incompitable Entities in
C
There are some entities in C for which we cannot use the address operator.
we cannot get the address of those entities in C. Some of them are:
 Register Variables
 Bit Fields
 Literals
 Expressions
Applications of Address Operator (&):
The address operator (&) is widely used in C programs to get the addresses of different entities.
Major and most common applications are:
 Passing Pointers as Function Arguments
 Pointer Arithmetic
 Implementing Data Structures
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
#include <stdio.h>
int main() {
Int a[2][3]={1,2,3,4,5};
Int i=0, j=0;
for(i=0;i<2;i++)

Guess the
for(j=0;j<3;j++)

output…
printf("%d",[i][j]);
}
return 0;
}

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


#include <stdio.h>
int main()
{
int x=10; //integer variable

Guess the int *ptrX; //integer pointer declaration


ptrX=&x; //pointer initialization with the address of x
output… printf("Value of x: %d\n",*ptrX);
return 0;
}

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


#include <stdio.h>
int main () {
int num = 10;
printf("The address of num is %p", &num);

Guess the return 0;


}
output…

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


#include <stdio.h>
void swap (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
Guess the }
int main() {
output… int x = 10, y = 20;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Coding Assignments
1. C program to transpose a matrix
2. Write a program in C to find the number occurring odd number of
times in an array.
All numbers occur even number of times except one number which
occurs odd number of times.
Expected Output :
The given array is : 8 3 8 5 4 3 4 3 5
The element odd number of times is : 3
3. Write a program in C to find the second smallest element in an array.

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


References
• https://beginnersbook.com/2014/01/2d-arrays-in-c-example/
• https://www.simplilearn.com/tutorials/data-structure-tutorial/two-
dimensional-arrays
• https://codedamn.com/news/c/how-to-use-pointers-with-2d-arrays-in-c
• https://www.geeksforgeeks.org/address-operator-in-c/
• https://www.includehelp.com/c/c-pointer-address-operators.aspx
• https://www.javatpoint.com/address-operator-in-c

11/12/2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


POINTER IN C
POINTER
• C pointer is the derived data type.

• Used to store the address of another variable.

• Used to access and manipulate the variable's data stored at that location.

• With pointers, you can

1. Access and modify the data located in the memory.


2. Pass the data efficiently between the functions.
3. Create dynamic data structures like linked lists, trees, and graphs.
POINTER Declaration
• To declare a pointer

data-type *p-var-name;

• data-type is the pointer's base type


• It must be a valid C data type
• The p-var-name is the name of the pointer variable.
• The asterisk * used to declare a pointer is the same asterisk used for multiplication.
However, in this statement the asterisk is being used to designate a variable as a
pointer.
POINTER Declaration

data-type *p-var-name;
 int *p; /* pointer to an integer */

 double *p; /* pointer to a double */

 float *p; /* pointer to a float */

 char *p /* pointer to a character */


POINTER Initialization

 After declaring a pointer variable, need to initialize it

With the address of another variable using the address of (&) operator.

data-type *p-var-name;

p-var-name = &var-name;
POINTER Initialization

Example:

int x = 10;

int *ptr = 10;

ptr = &x;

Here, x is an integer variable, ptr is an integer pointer.


Dereferencing Pointers

Dereferencing a pointer
using the * operator

To get the value from the


memory address that is
pointed by the pointer.
Dereferencing Pointers

• Change the Value

• Dereference to access or output it.


Size of a Pointer Variable

• The memory (or, size) occupied


by a pointer variable does not
depend on the type of the variable
it is pointing to.
• The size of a pointer depends on
the system architecture.

• 64 bit (64 bits)


• 32 bit (32 bits)
Pointer to Pointer

"y" will return the address of "x"


"*y" is the value in "x" (which is the address of "a").

• "a" is a normal "int" variable, whose pointer is "x".

• “y”is pointer to a pointer

• *x will give the 10

• *y will give 1000; **y will give 10.


Pointer to Pointer
11/12/2024
11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", *p); // Dereference pointer p
p++; // Move the pointer to the next integer in the array
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", a[i]); //
p++; //
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", i[a]); //
p++; //
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", a+i); //
p++; //
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", *(a+i)); //
p++; //
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // (same as &a[0])

for (i = 0; i < 5; i++)


{
printf("%d ", *(a)); //
p++; //
}

11/12/2024
Pointer to an array
#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50}; // Initialize an array
int *ptr = arr; // Point to the first element of the array
int length = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements

printf("Array elements using pointer arithmetic:\n");


for (int i = 0; i < length; i++) {
printf("%d ", *(ptr + i)); // Access each element using pointer arithmetic
}

printf("\n");
return 0;
}

11/12/2024
Pointer to an array
#include <stdio.h>

#define SIZE 5 printf("Sum: %d\n", sum);


printf("Maximum Value: %d\n", max);
int main() {
int arr[SIZE]; return 0;
int *ptr = arr; // Pointer to the array
int sum = 0, max = *ptr; // Initialize sum and max }

// Fill the array and calculate sum and max


for (int i = 0; i < SIZE; i++, ptr++) {
printf("Enter element %d: ", i + 1);
scanf("%d", ptr); // Fill using pointer arithmetic
sum += *ptr; // Access element for sum
if (*ptr > max) {
max = *ptr; // Update max using pointer arithmetic
}
}

11/12/2024
Pointer to an Array
#include <stdio.h>
// Read n integers into the array using the pointer
int main() { for (i = 0; i < n; i++) {
int *a; // Pointer to int printf("Enter element %d: ", i + 1);
int b[10] = {0}; // Array of 10 integers, initialized to 0 scanf("%d", a++);
int n; // Variable to hold the number of elements to read }
int i = 0; // Loop variable
// Reset pointer 'a' to point to the beginning of the array
// Point 'a' to the beginning of array 'b' a = b;
a = b;
// Print the elements of the array using the pointer
printf("The elements entered are:\n");
// Read the number of elements to input
for (i = 0; i < n; i++) {
printf("Enter the number of elements (max 10): ");
printf("%d\n", *a++);
scanf("%d", &n); }

// Ensure that n does not exceed the size of the array return 0; // Indicate successful completion
}
if (n > 10) {
printf("Please enter a number less than or equal to 10.\n");
}

11/12/2024
Array Memory Allocation

int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

11/12/2024
Pointer to Multidimensional Array
#include <stdio.h>
// Print the elements of the 2D array using the pointer
printf("The elements of the 3x3 matrix are:\n");
int main() {
for (i = 0; i < r; i++) {
int *a; // Pointer to int
for (j = 0; j < c; j++) {
int b[4][4]={0}; // 2D array of integers
printf("%d\t", *a++); // Print the current element and increment the
int r = 3, c = 3; // Number of rows and columns pointer
int i, j; // Loop variables }
printf("\n"); // New line after each row
// Read values into the 2D array }
printf("Enter %d elements for a 3x3 matrix:\n", r * c);
for (i = 0; i < r; i++) { return 0; // Indicate successful completion
for (j = 0; j < c; j++) { }
scanf("%d", &b[i][j]);
}
}

// Point 'a' to the first element of the array


a = (int *)b; // Casting 'b' to an integer pointer

11/12/2024
Pointer to Multidimensional Array
a B[0] 1 2 3 0
B[1] 4 5 6 0
B[2] 7 8 9 0
B[3] 0 0 0 0

Output
1 2 3
0 4 5
6 0 7

11/12/2024

You might also like