An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it.
int data[100];
dataType arrayName[arraySize];
For 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.
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]will be 2124d. Similarly, the address of mark[2] will be 2128d and so on. This is because the size of a float is 4 bytes.
It is possible to initialize an array during declaration. 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.
int mark[5] = {19, 10, 8, 17, 9}
// make the value of the third element to -1
mark[2] = -1;
// make the value of the fifth element to 0
mark[4] = 0;
Here's how you can take input from the user and store it in an array element.
// take input and store it in the 3rd element
scanf("%d", &mark[2]);
// take input and store it in the ith element
scanf("%d", &mark[i-1]);
Here's how you can print an individual element of an array.
// print the first element of the array
printf("%d", mark[0]);
// print the third element of the array
printf("%d", mark[2]);
// print ith element of the array
printf("%d", mark[i-1]);
Example of how you can take five characters from a user as a char array and print the result using a loop in C:
#include <stdio.h>
int main() {
char charArray[5];
int i;
printf("Enter five characters: ");
for (i = 0; i < 5; i++) {
scanf(" %c", &charArray[i]);
}
printf("The characters you entered are: ");
for (i = 0; i < 5; i++) {
printf("%c ", charArray[i]);
}
printf("\n");
return 0;
}
Here's how the code works:
We declare a character array called charArray with a size of 5 to store the five characters entered by the user.
We use a for loop to iterate five times (from 0 to 4) to read the characters from the user using scanf(). The %c format specifier is used to read a single character, and we use the address-of operator & to store each character in the corresponding element of the charArray.
After reading the characters, we use another for loop to iterate through the charArray and print each character using printf(). The %c format specifier is used to print a single character, and we separate each character with a space.
Finally, we print a newline character \n to move the cursor to the next line.
When you run this program, it will prompt the user to enter five characters. After the user enters the characters and presses Enter, the program will display the characters you entered.
For example, if the user enters "abcde", the output will be:
Enter five characters: abcde
The characters you entered are: a b c d e
Here's an example of using arrays in C to store and manipulate data:
Let's say we want to store a list of numbers and calculate their sum and average.
#include <stdio.h>
int main() {
int numbers[5];
int sum = 0;
float average;
// Input numbers
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &numbers[i]);
}
// Calculate sum
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
// Calculate average
average = (float)sum / 5;
// Output results
printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);
return 0;
}
In this example:
We declare an integer array numbers with a size of 5 to store 5 numbers.
We declare two variables: sum to store the sum of the numbers, and average to store the calculated average.
We prompt the user to enter 5 numbers and store them in the numbers array using a for loop and scanf().
We calculate the sum of the numbers by iterating through the numbers array and adding each element to the sum variable.
We calculate the average by dividing the sum by the number of elements (5) and storing the result in the average variable.
Finally, we output the sum and average using printf().
Output:
Enter 5 numbers:
10
20
30
40
50
Sum: 150
Average: 30.00
In this example, we used an array to store a list of numbers, and then performed operations like input, sum calculation, and average calculation on the array elements.
Multidimensional Arrays
Multidimensional arrays in C are arrays that contain other arrays as their elements, allowing for the storage of data in multiple dimensions. The most common types are two-dimensional (2D) and three-dimensional (3D) arrays, which can be visualized as matrices and cubes, respectively. This detailed explanation will cover their declaration, initialization, accessing elements, and provide multiple examples.
The general syntax for declaring a multidimensional array is:
data_type array_name[size1][size2]...[sizeN];
data_type: Type of data to be stored (e.g., int, float).
array_name: Name of the array.
size1, size2, ..., sizeN: Size of each dimension.
A 2D array can be declared as follows:
int matrix[3][4]; // A 2D array with 3 rows and 4 columns
This declaration creates an array that can hold 12 integer elements.
A 3D array can be declared similarly:
int cube[2][3][4]; // A 3D array with 2 layers, 3 rows, and 4 columns
This array can hold 24 integer elements.
To access an element in a multidimensional array, you specify the indices for each dimension. For example, to access the element in the first row and second column of a 2D array:
int value = matrix[0][1]; // Accesses the element at first row, second column
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
printf("Element at matrix[0][1]: %d\n", matrix[0][1]); // Outputs 2
return 0;
}
To traverse a multidimensional array, nested loops are used. Each loop corresponds to one dimension of the array.
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Element at matrix[%d][%d]: %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
#include <stdio.h>
int main() {
int cube[2][3][2] = { {{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 2; k++) {
printf("Element at cube[%d][%d][%d]: %d\n", i, j, k, cube[i][j][k]);
}
}
}
return 0;
}
In C, multidimensional arrays are stored in row-major order. This means that the elements of each row are stored in contiguous memory locations. For example, in a 2D array, all elements of the first row are stored before the elements of the second row.
Multidimensional arrays are widely used in various applications:
Image Processing: 2D arrays can represent pixel values in images.
Scientific Computing: They can model complex data structures, such as matrices in linear algebra.
Game Development: 3D arrays can represent three-dimensional spaces or grids.
Multidimensional arrays in C provide a powerful way to handle data in multiple dimensions, enabling complex data manipulation and storage. Understanding their declaration, initialization, and traversal is essential for effective programming in C. By practicing with various examples, programmers can become proficient in using multidimensional arrays for a wide range of applications.
Exercise: Working with Multidimensional Arrays
You are given a 2D array (matrix) representing the scores of students in a class across different subjects. Each row represents a different student, and each column represents a different subject.
The matrix is as follows:
int scores[][] = {
{85, 92, 78}, # Student 1 scores: Math, Science, English
{88, 79, 95}, # Student 2 scores: Math, Science, English
{90, 88, 91}, # Student 3 scores: Math, Science, English
{70, 85, 89} # Student 4 scores: Math, Science, English
};
Tasks:
Write a function average_scores(scores) that takes the 2D array as input and returns a list containing the average score of each student.
Write a function subject_averages(scores) that returns a list containing the average score for each subject across all students.
Determine which student has the highest average score and print their index (0-based) and average score.
C does not provide a built-in way to get the size of an array.
With that said, it does have the built-in sizeof operator, which you can use to determine the size.
The general syntax for using the sizeof operator is the following:
datatype size = sizeof(array_name) / sizeof(array_name[index]);
Let's break it down:
size is the variable name that stores the size of the array, and datatype specifies the type of data value stored in size.
sizeof(array_name) calculates the size of the array in bytes.
sizeof(array_name[index]) calculates the size of one element in the array.
Functions in C are reusable blocks of code that perform a specific task. They allow you to break down your program into smaller, more manageable pieces, making it easier to write, test, and maintain.
return_type function_name(parameter_list) {
// function body
// statements
return value;
}
return_type is the data type of the value returned by the function. It can be int, float, char, void, etc. If the function doesn't return anything, use void.
function_name is the name of the function.
parameter_list is a comma-separated list of parameters the function takes, if any. Each parameter has a data type and a name.
The function body contains the statements that define the function's behavior.
The return statement is used to return a value from the function. It can be omitted if the function has a return type of void.
Example:
int add(int a, int b) {
int result = a + b;
return result;
}
This function takes two integers as parameters, adds them, and returns the result.
A function prototype is a declaration of a function that specifies its return type, name, and parameters. It allows the compiler to know the function's interface before its definition.
return_type function_name(parameter_list);
The syntax is similar to the function definition, but without the function body.
Example:
int add(int, int);
This prototype declares a function named add that takes two integer parameters and returns an integer.
Function prototypes are typically placed at the beginning of a source file or in a header file.
They allow the compiler to perform type checking on function calls, ensuring that the correct number and types of arguments are passed.
If a function is called before its definition, the compiler uses the prototype to validate the call.
Example:
#include <stdio.h>
int add(int, int); // Function prototype
int main() {
int result = add(5, 10);
printf("Result: %d\n", result);
return 0;
}
int add(int a, int b) { // Function definition
return a + b;
}
In this example, the function prototype int add(int, int); is declared before main(). The actual function definition follows later in the code.
Void Function
A void function in C is a function that does not return a value. It performs a specific task but does not provide any output to the calling function. Below is a simple example of a void function that prints a greeting message to the console.
#include <stdio.h>
// Function prototype
void printGreeting();
int main() {
// Calling the void function
printGreeting();
return 0;
}
// Definition of the void function
void printGreeting() {
printf("Hello, welcome to the world of C programming!\n");
}
In C programming, the main function serves as the entry point for program execution. Every C program must have a main function, and it is where the execution of the program begins. The operating system calls this function when the program is run.
The main function can be defined in a couple of ways, but the most common signatures are:
int main(void) {
// function body
return 0;
}
or
int main(int argc, char *argv[]) {
// function body
return 0;
}
Return Type: The main function returns an int, which is a status code to the operating system. A return value of 0 typically indicates successful execution, while a non-zero value indicates an error.
Parameters:
int argc: This parameter counts the number of command-line arguments passed to the program, including the program's name itself.
char *argv[]: This is an array of strings (character pointers) that holds the actual command-line arguments. Each element in this array is a string representing one of the arguments.
Here’s a simple example of a C program that demonstrates the main function:
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
Here’s an example that uses command-line arguments:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
argc: This will contain the number of command-line arguments passed to the program.
argv: This array holds the actual arguments. The first element (argv) is the name of the program, and the subsequent elements are the arguments provided by the user.
If you compile the above program and run it from the command line like this:
./my_program arg1 arg2
The output will be:
Number of arguments: 3
Argument 0: ./my_program
Argument 1: arg1
Argument 2: arg2
The main function is essential for any C program, serving as the starting point for execution.
It can be defined with or without parameters, depending on whether you need to handle command-line arguments.
Always return an integer value from main to indicate the success or failure of the program.
Understanding the main function is crucial for writing effective C programs, as it sets the stage for the entire program's execution flow.
Immediate Availability: When functions are defined before main, they can be called directly without needing a prototype. This can simplify the code structure, especially for smaller programs.
Readability: For some programmers, having functions defined before main can enhance readability, as the main logic of the program is immediately followed by the functions that support it.
Prototyping: If functions are defined after main, it is necessary to declare their prototypes before main. This practice can make the code easier to understand, as the prototypes provide a summary of the functions used in main.
Logical Flow: For larger programs, defining main first can provide a clearer overview of the program's flow, with the supporting functions following. This can help readers quickly grasp the main logic before delving into the details of each function.