UNIT IV C Porgramming
UNIT IV C Porgramming
Arrays in C are one of the most fundamental and powerful tools for managing data collections.
Whether you're storing a list of integers, managing a sequence of characters, or working with
complex data structures, arrays provide an efficient way to handle data systematically.
Syntax
data_type array_name[array_size];
data_type: Specifies the type of elements the array will hold (e.g., int, float, char).
array_name: The identifier for the array.
array_size: The number of elements the array can hold (must be a positive integer).
int numbers[5];
float prices[10];
Arrays are essential in C programming because they allow us to store and manage multiple
elements of the same data type using a single variable. Instead of declaring separate variables
for each element, arrays provide a structured way to handle data collection, making programs
more efficient and easier to read. They are beneficial for tasks like managing lists, performing
mathematical operations on datasets, and handling data sequences in loops.
Properties of Arrays in C
1. Arrays have a fixed size determined at the time of declaration.
2. Array elements are stored in contiguous memory locations.
3. All elements in an array must be of the same data type.
4. The first element is accessed with index 0.
5. Accessing out-of-bound indices leads to undefined behavior.
6. Arrays are passed to functions by reference.
7. The name of the array represents the address of its first element.
Access Array Elements
Array elements can be accessed using their index values. The index starts at 0, so the first element
is at position 0, the second at position 1, and so on.
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Declare and initialize an array
// Accessing elements
printf("First element: %d\n", arr[0]);
printf("Third element: %d\n", arr[2]);
return 0;
}
Input and Output Array Elements
#include <stdio.h>
int main() {
int arr[3];
// Input elements
printf("Enter 3 integers: ");
for (int i = 0; i < 3; i++) {
scanf("%d", &arr[i]);
}
// Output elements
printf("You entered: ");
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Printing array elements (already initialized)
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
// Print elements
for (int i = 0; i < 3; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}
return 0;
}
Advantages of Arrays in C
1. Efficient Memory Usage: Arrays provide a way to store data sequentially, reducing
memory wastage.
2. Easy Data Access: Elements can be accessed directly using their indices.
3. Compact Code: Using loops, operations can be performed on multiple elements, reducing
repetitive code.
4. Static Storage: Data is allocated contiguously, enabling faster access and manipulation.
5. Ideal for Fixed-Size Data: Arrays are perfect when the number of elements is known in
advance.
Disadvantages of Arrays in C
1. Fixed Size: The size of an array must be defined at the time of declaration, limiting
flexibility.
2. Homogeneous Data: Arrays can only store elements of the same data type.
3. No Built-in Bounds Checking: Accessing indices outside the declared range can lead to
undefined behavior.
4. Insertion and Deletion: These operations are time-consuming as they require shifting
elements.
5. Memory Allocation: If improperly handled, large arrays can lead to excessive memory
usage.
Multidimensional Array
2-Dimensional Array in C
data_type array_name[rows][columns];
int arr[3][4]; // Declares a 2D array with 3 rows and 4 columns
Initialization
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6} };
Points to Remember While Initializing a 2D Array:
1. The total number of elements must not exceed rows * columns.
2. Omitted elements are automatically initialized to 0.
3. Use nested braces for better readability.
Printing a 2D Array (Matrix)
#include <stdio.h>
int main() {
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Addition of 2D Array
#include <stdio.h>
int main() {
int arr[2][2] = {
{1, 2},
{3, 4}
};
int sum = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum += arr[i][j];
}
}
printf("Sum: %d\n", sum);
return 0;
}
Arrays vs. Pointers
The size of an array is fixed and The size of memory accessed through
Size
known at compile time. pointers is flexible.
1. Input the Array: Read the array elements from the user.
2. Input the Element to Search: Read the element to be searched by the user.
3. Search the Array: Iterate through the array to find the element.
4. Print the Result: Output the result indicating whether the element was found and its
position.
#include <stdio.h>
int main() {
int size, element, found = 0;
// Input size and elements of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements -\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Input the element to search
printf("\nEnter the element to search: ");
scanf("%d", &element);
C Programming Strings
char s[5];
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
String Functions:
1. strlen() Function
The strlen() function is used to calculate the length of a string. It returns the number of characters
in the string, excluding the null terminator ('\0').
The strlen() function returns the length of a string, which is the number of characters up to the
first null terminating character. This is smaller than the amount of memory that is reserved for
the string, which can be measured using the sizeof operator instead.
If the end of both strings has been reached without any mismatches then the function
returns zero.
At the first mismatch, if the ASCII value of the character in the first string is greater then
the function returns a positive number.
At the first mismatch, if the ASCII value of the character in the second string is greater
then the function returns a negative number.
The strcpy() function copies data from one string into the memory of another string.
The strcpy() function is defined in the <string.h> header file.
Note: Make sure that the destination string has enough space for the data or it may start writing
into memory that belongs to other variables.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50];
char str2[] = "Copy this string!";
strcpy(str1, str2);
printf("Copied String: %s\n", str1);
return 0;
}
strcat() Function
The strcat() function is used to concatenate (append) one string to the end of another. The source
string is appended to the destination string.
The strncat() function appends part of a string to the end of another. A number specifies the size
of the part of the string to append. The strncat() function is defined in the <string.h> header file.
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
return 0;
}
C Pointers
A pointer is defined as a derived data type that can store the memory address of other variables,
functions, or even other pointers. It is one of the core components of the C programming
language allowing low-level memory access, dynamic memory allocation, and many other
functionalities in C.
Syntax of C Pointers
The syntax of pointers depends on the type they are pointing to. In general, for a variable, a
pointer can be declared as:
type*ptr;
where,
The (*) dereferencing operator is used to denote that the declared variable is stores the
address of another variable
#include <stdio.h>
int main() {
// An integer variable
int a = 10;
return 0;
}
Output
ptr = 0x7fffa0757dd4
*ptr = 10
Pointer Declaration
1. To declare a pointer, we use the (*) dereference operator before its name. In pointer
declaration, we only declare the pointer but do not initialize it.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer
variable. We use the (&) addressof operator to get the memory address of a variable and
then store it in the pointer variable.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same (*) dereferencing operator that we
used in the pointer declaration.
#include <stdio.h>
int main() {
int a = 10;
Output
Value at ptr = 0x7ffd97e566dc
Value at a = 10
Value at *ptr = 10