Understanding One-Dimensional Arrays in C Programming

Slide Note
Embed
Share

Arrays in C are collections of variables of the same data type that allow storing a group of data. This article covers the basics of one-dimensional arrays in C, explaining syntax, declaration, initialization, and accessing elements. It also provides examples and a sample program to demonstrate array usage and manipulation.


Uploaded on Aug 04, 2024 | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. C-ARRAY

  2. C Array is a collection of variables belongings to the same data type. Group of data of same data type can be stored in an array. Array might be belonging to any of the data types e.g. Float, int, double, etc. Array size must be a constant value. Always, Contiguous (adjacent) memory locations are used to store array elements in memory. It is a best practice to initialize an array to zero or null while declaring, if we do not assign any values to array.

  3. Example for C Arrays: int x[20]; char y[10]; // character array i.e. string // integer array Types of C arrays: There are 2 types of C arrays. They are, One dimensional array Multi dimensional array Two dimensional array Three dimensional array, four dimensional array etc

  4. One dimensional array in C: Syntax : data-type arr_name[array_size]; Array Declaration Array Initialization Accessing Array Syntax: data_type arr_name [arr_size]; data_type arr_name [arr_size]=(value1, value2, value3, .); arr_name[index]; int age [5]; age[0];_/*0_is_accessed*/age[1];_/ *1_is_accessed*/age[2];_/*2_is_acc essed*/ int age[5]={0, 1, 2, 3, 4}; char str[10]; char str[10]={ H , a , i }; (or)char str[0] = H ;char str[1] = a ; char str[2] = i; str[0];_/*H is accessed*/str[1]; /*a is accessed*/str[2]; /* i is accessed*/

  5. /* The following program declares an array of five integers, assigns the values 10, 20, 30, 40, and 50 to its elements, and displays those greater than 20.*/ #include <stdio.h> int main(void) { int i, arr[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for(i = 0; i < 5; i++) { /* The braces are not necessary; we use them to make the code clearer. */ if(arr[i] > 20) printf("%d\n", arr[i]); } return 0; }

  6. /* Write a program that declares an array of five elements and uses a for loop to assign the values 1.1, 1.2, 1.3, 1.4, and 1.5 to them. Then, the program should display the array s elements in reverse order. */ #include <stdio.h> int main(void) { int i; double arr[5]; arr[0] = 1.1; for(i = 1; i < 5; i++) arr[i] = arr[i-1] + 0.1; for(i = 4; i >= 0; i--) printf("%f\n", arr[i]); return 0; }

  7. // Example program for one-dimensional array #include<stdio.h> int main(){ int i; int arr[5] = {10,20,30,40,50}; // declaring and Initializing array in C //To initialize all array elements to 0, use int arr[5]={0}; /* Above array can also be initialized as follows: arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; */ for (i=0;i<5;i++) { // Accessing each variable printf( value of arr[%d] is %d \n , i, arr[i]); } }

  8. Two Dimensional Array The form of a two-dimensional array resembles that of a matrix in math; it is an array of elements of the same type arranged in rows and columns. syntax data_type array_name [num_of_rows][num_of_column] The number of its elements is equal to the product of rows multiplied by columns. For example, the statement double arr[10][5]; declares the two-dimensional array arr with 50 elements of type double. Array Declaration Array Initialization Accessing Array Syntax: data_type arr_name [num_of_rows][num_of_c olumn]; data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}}; arr_name[index]; Example:int arr[2][2]; int arr[2][2] = {1,2, 3, 4}; arr [0] [0] = 1; arr [0] ]1] = 2;arr [1][0] = 3; arr [1] [1] = 4;

  9. //Example program for C- array #include<stdio.h> int main(){ int i,j; // declaring and Initializing array int arr[2][2] = {10,20,30,40}; /* Above array can be initialized as below also arr[0][0] = 10; // Initializing array arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; */ for (i=0;i<2;i++) { for (j=0;j<2;j++) { // Accessing variables printf( value of arr[%d] [%d] : %d\n ,i,j,arr[i][j]); } } }

  10. /* Write a program that reads 8 integers, stores them in a 24 array, and displays the array elements in reverse order, from the lower-right element to the upper-left one. */ #include <stdio.h> #define ROWS 2 #define COLS 4 int main(void) { int i, j, arr[ROWS][COLS]; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { printf("Enter arr[%d][%d]: ", i, j); scanf("%d", &arr[i][j]); } } printf("\nArray elements\n"); printf("--------------\n"); for(i = ROWS-1; i >= 0; i--) for(j = COLS-1; j >= 0; j--) printf("arr[%d][%d] = %d\n", i, j, arr[i][j]); return 0; }

  11. /* Write a program that reads and stores the grades of 100 students in 10 courses in a 100 10 array and displays the average, the best, and the worst grade of each student. The program should also display the positions in the array that hold the best and worst average grades. If more than one student has the same best or worst average grade, the program should display the first position found. The program should force the user to enter grades within [0, 10]. */ #include <stdio.h> #define STUDS 100 #define COURSES 10

  12. int main(void) { int i, j, min_pos, max_pos; float sum, min_grd, max_grd, avg_grd, min_avg_grd, max_avg_grd, grd[STUDS][COURSES]; max_avg_grd = 1; min_avg_grd = 11; for(i = 0; i < STUDS; i++) { sum = 0; max_grd = 1; min_grd = 11; for(j = 0; j < COURSES; j++) { do { printf("Enter grade of student_%d for lesson_%d: ", i+1, j+1); scanf("%f", &grd[i][j]); } while(grd[i][j] < 0 || grd[i][j] > 10); sum += grd[i][j]; if(grd[i][j] >= max_grd)

  13. max_grd = grd[i][j]; if(grd[i][j] <= min_grd) min_grd = grd[i][j]; } avg_grd = sum/COURSES; if(avg_grd > max_avg_grd) { max_avg_grd = avg_grd; max_pos = i; } if(avg_grd < min_avg_grd) { min_avg_grd = avg_grd; min_pos = i; } printf("Student_%d: Avg = %.2f Max = %.2f Min = %.2f\n", i+1, avg_grd, max_grd, min_grd); } printf("\nStudent_%d has the higher average %.2f and student_%d has the lower average %.2f\n", max_pos, max_avg_grd, min_pos, min_avg_grd); return 0; }

  14. /* Write a program that reads integers and stores them in a square matrix (e.g., 3 3). Then, the program should check whether the array is a magic square; that is, the sum of each row, column, and diagonal is the same. */ #include <stdio.h> #define ROWS 3 #define COLS 3 int main(void) { int i, j, sum, tmp, arr[ROWS][COLS]; //column, and diagonal is the same. sum = tmp = 0; for(i = 0; i < ROWS; i++) {

  15. /* We find the sums of the diagonals. */ for(j = 0; j < COLS; j++) { printf("Enter element arr[%d][%d]: ", i, j); scanf("%d", &arr[i][j]); if(i == j) sum += arr[i][j]; if(i+j == ROWS-1) /* Check if the element belongs in the secondary diagonal. */ tmp += arr[i][j]; } } if(sum != tmp) { printf("Not magic square -> Sum_main_diag: %d Sum_sec_diag: %d\n", sum, tmp); return 0; }

  16. for(i = 0; i < ROWS; i++) { /* Initialize the variable which calculates the sum of the elements of each row. */ tmp = 0; for(j = 0; j < COLS; j++) tmp += arr[i][j]; if(sum != tmp) { printf("Not magic square -> Sum_row_%d: %d Sum_diag: %d\n", i+1, tmp, sum); return 0; }

  17. } for(i = 0; i < COLS; i++) { tmp = 0; /* Initialize the variable which calculates the sum of the elements of each column. */ for(j = 0; j < ROWS; j++) tmp += arr[j][i]; if(sum != tmp) { printf("Not magic square -> Sum_col_%d: %d Sum_diag: %d\n", i+1, tmp, sum); return 0; } } printf("Magic square !!!\n"); return 0;

  18. C-POINTER

  19. C Pointer is a variable that stores/points the address of another variable. C Pointer is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc. Syntax : data_type *var_name; Example : int *p; char *p; Where, * is used to denote that p is pointer variable and not a normal variable. Key points to remember about pointers in C: Normal variable stores the value whereas pointer variable stores the address of the variable. The content of the C pointer is always a whole number i.e. address. Always C pointer is initialized to null, i.e. int *p = null. The value of null pointer is 0. & symbol is used to get the address of the variable.

  20. * symbol is used to get the value of the variable that the pointer is pointing to. If pointer is assigned to NULL, it means it is pointing to nothing. Two pointers can be subtracted to know how many elements are available between these two pointers. But, Pointer addition, multiplication, division are not allowed. The size of any pointer is 2 byte (for 16 bit compiler).

  21. // example program for pointer in c #include <stdio.h> int main() { int *ptr, q; q = 50; /* address of q is assigned to ptr */ ptr = &q; /* display q s value using ptr variable */ printf( %d , *ptr); return 0; } .

  22. // What is the output of the following program? #include <stdio.h> int main(void) { int *ptr, i = 10; ptr = &i; i += 20; printf("%d\n", *ptr); return 0; } Answer: Since ptr points to the address of i, *ptr is equal to i. The statement i += 20; makes i equal to 30, and the program outputs 30.

  23. /* Write a program that reads two integers, stores them in two variables, declares two pointers to them, and displays the memory addresses of both variables, the content of both pointers, as well as their memory addresses.*/ #include <stdio.h> int main(void) { int *ptr1, *ptr2, i, j; printf("Enter numbers: "); scanf("%d%d", &i, &j); ptr1 = &i; ptr2 = &j; printf("Num1 address = %p\n", ptr1); printf("Num2 address = %p\n", ptr2); printf("Ptr1 content = %d\n", *ptr1); printf("Ptr2 content = %d\n", *ptr2); printf("Ptr1 address = %p\n", &ptr1); printf("Ptr2 address = %p\n", &ptr2); return 0; }

  24. /* Write a program that uses a pointer to read a float number and display its absolute value. */ #include <stdio.h> int main(void) { double *p, val; p = &val; printf("Enter number: "); scanf("%lf", p); if(*p >= 0) printf("%f\n", *p); else printf("%f\n", -*p); return 0; }

  25. /*Write a program that uses two pointers to read two float numbers first and then to swap the values they point to. Then, use the same pointers to output the greater value. */ #include <stdio.h> int main(void) { float *ptr1, *ptr2, i, j, tmp; /* The pointers should be initialized before used in scanf(). */ ptr1 = &i; ptr2 = &j; printf("Enter values: "); scanf("%f%f", ptr1, ptr2); /* Store the input values in the addresses pointed to by the pointers. */ tmp = *ptr2; *ptr2 = *ptr1; *ptr1 = tmp; if(*ptr1 > *ptr2) printf("%f\n", *ptr1); else printf("%f\n", *ptr2); return 0; }

  26. //What is the output of the following program? #include <stdio.h> int main(void) { int i = 0, *ptr = &i; *ptr = *ptr ? 10 : 20; printf("%d\n", i); return 0; } Answer: Since ptr points to the address of i, the expression: *ptr = *ptr ? 10 : 20; is equivalent to i = i ? 10 : 20; Since i is 0 (false), the value of the expression is 20. Therefore, i becomes 20 and the program outputs 20.

Related


More Related Content