0% found this document useful (0 votes)
32 views11 pages

UNIT IV C Porgramming

Uploaded by

sahastracasual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views11 pages

UNIT IV C Porgramming

Uploaded by

sahastracasual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT – IV

Array in C: Declaration, Advantages, & Examples:

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.

Array in C is a collection of variables stored in contiguous memory locations. It can be accessed


using a single name and an index. These entities or elements can be int, float, char, double, or
user-defined data types, like structures.

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];

 The array size must be a constant value defined at compile time.


 If the size is omitted during the declaration, it must be determined from the initialization.
Initialization

int numbers[5] = {1, 2, 3, 4, 5}; // Initializes all elements


int numbers[5] = {1, 2}; // Initializes first two elements; remaining are set to 0

int numbers[] = {1, 2, 3}; // Size is automatically set to 3

char name[] = "Alice"; // Automatically includes the null terminator '\0'

Why Do We Need Arrays?

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.

One Dimensional Array in C


int arr[5] = {1, 2, 3, 4, 5};

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

Aspect Arrays Pointers

An array is a collection of elements


A pointer is a variable that stores the
Definition of the same type stored in
memory address of another variable.
contiguous memory locations.

Memory can be allocated


Memory Memory is allocated at compile-
dynamically at runtime using
Allocation time for a fixed size.
functions like malloc or calloc.

The size of an array is fixed and The size of memory accessed through
Size
known at compile time. pointers is flexible.

Access elements using indices (e.g., Access data indirectly by


Access
arr[2]). dereferencing (e.g., *(ptr + 2)).

Arrays are pointers to the first Pointers provide greater flexibility


Relationship element but with additional but require manual manipulation of
indexing support. memory addresses.

Steps to Search for an Element in an Array

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);

// Search the array


for (int i = 0; i < size; i++) {
if (arr[i] == element) {
found = 1;
printf("Element %d found at position %d", element, i + 1);
break;
}
}
if (!found) {
printf("Element %d not found in the array", element);
}
return 0;
}

C Programming Strings

char s[5];

How to initialize strings?


 char c[] = "abcd";

 char c[50] = "abcd";

 char c[] = {'a', 'b', 'c', 'd', '\0'};

 char c[5] = {'a', 'b', 'c', 'd', '\0'};


Read String from the user
The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Enter name: Dennis Ritchie


Your name is Dennis.

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.

char myStr[20] = "Hello World";


printf("%zu\n", strlen(myStr));
printf("%zu\n", sizeof(myStr));

C string strncmp() function


The strcmp() function compares two strings and returns an integer indicating which one is
greater. For this comparison characters at the same position from both strings are compared
one by one, starting from the left until one of them does not match or the end of a string has
been reached. There are three possible scenarios:

 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.

Compare two strings to see which is greater:

char myStr1[] = "ABCD";


char myStr2[] = "ABCE";
int cmp = strcmp(myStr1, myStr2);
if (cmp > 0) {
printf("%s is greater than %s\n", myStr1, myStr2);
} else if (cmp < 0) {
printf("%s is greater than %s\n", myStr2, myStr1);
} else {
printf("%s is equal to %s\n", myStr1, myStr2);
}

C string strcpy() function

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.

Note: To append an entire string to another, use strcat() instead.


#include <stdio.h>
#include <string.h>

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,

 ptr is the name of the pointer.


 type is the type of data it is pointing to.

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;

// Create a pointer to integer (declaration)


int * ptr;

// Store the address of a inside pointer (initialization)


ptr = &a;

// Print the content of ptr


printf("ptr = %p\n", ptr);

// Get the value pointed by ptr (dereferencing)


printf("*ptr = %d", *ptr);

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;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &a;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at a = %d \n", a);
printf("Value at *ptr = %d \n", *ptr);
return 0;
}

Output
Value at ptr = 0x7ffd97e566dc
Value at a = 10
Value at *ptr = 10

You might also like