FOC Unit 3: Array, String and Functions

 

  • Whenever we want to work with large number of data values, we need to use that much number of different variables.
  • As the number of variables are increasing, complexity of the program also increases and programmers get confused with the variable names.

To understand the concept of arrays, consider the following example declaration.
int a, b, c;
Here, the compiler allocates 2 bytes of memory with name ‘a’, another 2 bytes of memory with name ‘b’ and more 2 bytes with name ‘c’.

These three memory locations are may be in sequence or may not be in sequence.


Array:

There may be situations in which we need to work with large number of similar data values.

To make this work more easy,
C/C++ programming language provides a concept called “Array”.
Python: list

An array is a variable which can store multiple values of same data type at a time.

Definition

An array is a collection of elements of the same data type stored in contiguous memory locations.

Array indices start from 0.

Types of Arrays

One-Dimensional (1D)int a[5];

Two-Dimensional (2D)int a[3][3];

Syntax

data_type array_name[size];

Example:

int num[5];

Initialization

int num[5] = {10, 20, 30, 40, 50};
Or
int num[] = {10, 20, 30, 40, 50}; // Size is auto-calculated

Accessing Elements

printf("%d", num[0]); // Access first element num[2] = 100; // Modify third element

Array with Loops

for (int i = 0; i < 5; i++) printf("%d ", num[i]);

Memory Representation:
Elements are stored sequentially in memory.
array[i] address = base_address + (i * sizeof(data_type))


2D Array Example

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
printf("%d", matrix[1][2]); // Output: 6

2D Array with Loop

#include <stdio.h> int main() { int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; // Display elements using nested loops for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; }
🔹Limitations
Fixed size (cannot grow/shrink at runtime)
All elements must be of the same type
No built-in bounds checking

🔹 Applications
Storing lists, matrices, strings
Implementing data structures (stacks, queues)
Sorting and searching algorithms


String:
-> A string in C is a sequence of characters stored in a character array, and is terminated by the null character '\0'

-> C doesn’t have a built-in “string” data type like some higher-level languages. Instead you work with char[] or char *

Example:

char str[] = "Hello";

This actually stores:
{'H', 'e', 'l', 'l', 'o', '\0'}

Declaring Strings

By character array:

    char name[10] = "Amit";

By character array without initialization:

    char name[10];

    Then assign using input:

    scanf("%s", name); // No '&' needed

String Input & Output

Input: scanf("%s", str);

Output: printf("%s", str);

Gets and puts (safer for spaces):

    gets(str); // reads line (unsafe)

    puts(str); // prints line


Declaration & Initialization

Here are ways to declare and initialize strings: char s1[] = "Hello"; // compiler infers size (6 chars: 'H','e','l','l','o','\0') char s2[10] = "Hi"; // explicit size, with room for more characters + '\0' char s3[] = {'C','\0'}; // initializing manually with null terminator char *s4 = "World"; // pointer to string literal (in read-only memory)

Input & Output of strings

To print a string you typically use printf("%s", s);. The %s specifier expects a char * pointing to a null-terminated array.

To read a string you can use functions like scanf("%s", s); (but this stops at whitespace).

For input including spaces you can use fgets(s, size, stdin); which reads a whole line including spaces up to size-1 characters.

Here is a list of common string operations (functions) in C:

strlen() — Determine the length of a string

strcpy() — Copy one string into another
strncpy() — Copy up to n characters from one string into another
strcat() — Concatenate (append) one string to the end of another
strstr() — Find the first occurrence of a substring in a string1.
strlen() — determine the length of a string

Syntax:
size_t strlen(const char *str);

Example program:
#include <stdio.h>
#include <string.h> int main(void) {
char s[] = "Hello, world!";
size_t len = strlen(s);
printf("String: \"%s\"\n", s); printf("Length (excluding '\\0'): %zu\n", len);

return 0; }}

Output: String: "Hello, world!" Length (excluding '\0'): 13

strcpy() — copy one string into another
Syntax:

char *strcpy(char *dest, const char *src);

Example program:
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "Copy this"; char dest[50]; // must be large enough to hold src + '\0'
strcpy(dest, src); printf("Source: \"%s\"\n", src); printf("Destination after copy: \"%s\"\n", dest); return 0; }
}
}
  • Example Program

    #include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[20] = "World"; strcat(str1, str2); printf("Concatenated String: %s\n", str1); printf("Length: %lu\n", strlen(str1)); return 0; }

    Output:

    Concatenated String: HelloWorld Length: 10

Post a Comment

0 Comments