Skip to main content

Arrays and Strings in C: Organizing Data the Smart Way

 

At some point in programming, individual variables stop being enough.
Storing one number is easy. Storing a hundred? That’s when arrays arrive like neatly labeled shelves, and strings step in as civilized ways to handle text.

UNIT III is about learning how to organize, process, and manipulate collections of data efficiently. It’s where C begins to feel powerful rather than primitive.


1. Arrays: Storing More with Less Effort

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

Instead of this:

int a, b, c, d, e;

You write this:

       int marks[5];

One name. Many values. Clean and efficient.

2. Declaring and Referencing Arrays

Declaration

int numbers[10];

This creates space for 10 integers.

Referencing Elements

Each element is accessed using an index (subscript), starting from 0.

numbers[0] = 10; numbers[1] = 20;

Visual Layout

Index: 0 1 2 3 4 Value: 10 20 30 40 50

Indexing mistakes are common — and unforgiving. C trusts you completely.


3. Sequential Access Using for Loops

Arrays and loops are best friends.

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

This pattern appears everywhere: reading input, processing data, computing totals, searching, sorting.


4. Using Array Elements as Function Arguments

You can pass individual elements:

printValue(arr[2]);

Or pass the entire array:

processArray(arr, size);

Inside the function, the array behaves like a pointer to its first element.

void processArray(int a[], int n) { for (int i = 0; i < n; i++) printf("%d ", a[i]); }

Arrays are always passed by reference, meaning changes inside the function affect the original array.


5. Searching an Array

Linear Search

Check each element until the target is found.

for (int i = 0; i < n; i++) { if (arr[i] == key) { found = 1; break; } }

Simple, reliable, and perfect for small datasets.


6. Sorting an Array

Sorting brings order to chaos.

Bubble Sort (Conceptual Favorite)

for (i = 0; i < n-1; i++) { for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { swap(arr[j], arr[j+1]); } } }

Though not the fastest, it’s excellent for understanding comparison-based sorting.


7. Parallel Arrays and Enumerated Types

Parallel Arrays

Used when related data must stay aligned.

int rollNo[3] = {1, 2, 3}; int marks[3] = {85, 90, 78};

Index i connects roll number with its marks.

Enumerated Types

Enums make code readable and meaningful.

enum Day {MON, TUE, WED, THU, FRI};

Now MON is clearer than 0.


8. Multidimensional Arrays

Multidimensional arrays represent tables, matrices, and grids.

int matrix[3][3];

Access

matrix[1][2] = 10;

Memory View

[ ][ ][ ] [ ][ ][ ] [ ][ ][ ]

Nested loops are essential here.

for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) printf("%d ", matrix[i][j]);

Strings in C: Text with Discipline

Unlike many languages, C treats strings as character arrays ending with a special character: '\0'.

char name[10] = "C Language";

In memory:

C L a n g u a g e \0

The null character marks the end.


9. String Basics and Library Functions

C provides powerful string-handling tools via <string.h>.

Assignment and Copy

strcpy(dest, src);

Length

strlen(str);

Substring

Handled using pointers and functions like strncpy().


10. Concatenation and Whole-Line Input

Concatenation

strcat(str1, str2);

Whole-Line Input

Avoid unsafe functions like gets(). Prefer:

fgets(name, sizeof(name), stdin);

It respects boundaries — something C programmers deeply value.


11. String Comparison

strcmp(str1, str2);

Returns:

  • 0 if equal

  • Negative if str1 < str2

  • Positive if str1 > str2

String comparison is lexical, not numerical.


12. Arrays of Pointers

Instead of a 2D character array:

char names[3][20];

You can use:

char *names[] = {"Alice", "Bob", "Charlie"};

Advantages:

  • Saves memory

  • Flexible string lengths

  • Faster access

This concept quietly prepares you for dynamic memory and advanced data structures.


Why UNIT III Matters

Arrays and strings teach data organization, not just syntax.
They help you think in collections, patterns, and structures — essential for real-world problem solving.

From student records to text processing, from matrices to menus, UNIT III concepts appear everywhere in C programming.

Master them well, and C stops feeling rigid. It starts feeling precise.

PART A: Multiple Choice Questions (MCQs)

1. Array indexing in C starts from

A. 1
B. 0
C. –1
D. Depends on compiler

Answer: B


2. Which of the following declares an integer array of size 20?

A. int a;
B. int a[20];
C. array int a[20];
D. int a(20);

Answer: B


3. The name of an array represents

A. Last element address
B. Address of the first element
C. Value of the first element
D. Size of the array

Answer: B


4. Which loop is most suitable for sequential access of arrays?

A. while
B. do-while
C. for
D. if

Answer: C


5. When an array is passed to a function, it is passed

A. By value
B. By reference
C. As a structure
D. As a constant

Answer: B


6. Which searching technique checks each element one by one?

A. Binary search
B. Linear search
C. Hash search
D. Tree search

Answer: B


7. Bubble sort works by

A. Dividing the array
B. Swapping adjacent elements
C. Selecting minimum elements
D. Using recursion

Answer: B


8. Parallel arrays are used to

A. Store multidimensional data
B. Store different types of unrelated data
C. Store related data using same index
D. Replace structures

Answer: C


9. Which keyword is used to define enumerated types?

A. enum
B. define
C. typedef
D. struct

Answer: A


10. A two-dimensional array is also called

A. Linear array
B. Pointer array
C. Matrix
D. Structure

Answer: C


11. Strings in C are terminated by

A. newline
B. space
C. null character ('\0')
D. tab

Answer: C


12. Which header file supports string functions?

A. stdio.h
B. math.h
C. string.h
D. stdlib.h

Answer: C


13. Which function compares two strings?

A. strcmp()
B. strcpy()
C. strcat()
D. strlen()

Answer: A


14. Which function is used to concatenate strings?

A. strcpy()
B. strcmp()
C. strcat()
D. strlen()

Answer: C


15. Which is safer for reading a full line of input?

A. gets()
B. scanf("%s")
C. fgets()
D. getchar()

Answer: C


16. Arrays of pointers are useful because they

A. Use more memory
B. Restrict string size
C. Allow variable-length strings
D. Eliminate loops

Answer: C


17. Which of the following is a valid string declaration?

A. char s = "Hello";
B. char s[6] = "Hello";
C. char s[5] = "Hello";
D. string s = "Hello";

Answer: B


18. Binary search requires the array to be

A. Large
B. Unsorted
C. Sorted
D. Reversed

Answer: C


19. Which operator is used to access elements of a multidimensional array?

A. *
B. .
C. []
D. ->

Answer: C


20. What does strlen() return?

A. Size of array
B. Length including \0
C. Number of characters excluding \0
D. Number of words

Answer: C


PART B: Short-Answer Questions (2–4 Marks)

  1. Define an array.

  2. Explain array subscripting with an example.

  3. Why are for-loops preferred for array processing?

  4. What happens when an array is passed to a function?

  5. Write the syntax for declaring a two-dimensional array.

  6. Explain linear search with an example.

  7. What is bubble sort? Write its basic logic.

  8. Define parallel arrays. Give one example.

  9. What is an enumerated data type? Why is it useful?

  10. Explain multidimensional arrays with a diagram.

  11. What is a string in C? How is it stored in memory?

  12. Why is '\0' important in strings?

  13. Differentiate between strcpy() and strcat().

  14. Why is gets() unsafe?

  15. What are arrays of pointers? Mention one advantage.


PART C: Very Short Answers (1 Mark)

  1. Default starting index of an array?

  2. Header file for string functions?

  3. Function to compare strings?

  4. Search method that checks sequentially?

  5. Keyword used for enumeration?

  6. Character used to terminate strings?

  7. Name one sorting technique.

  8. Function to read whole line input safely?



Comments

Popular posts from this blog

Designing Smarter C Programs: Top-Down Thinking, Functions, and Pointers

 In the early days of learning C, most programs feel like long stories without chapters. Everything lives inside main() , tangled and noisy. But real problem solving in programming begins when you learn to divide , delegate , and design cleanly. That’s where top-down design , functions , and pointers step into the spotlight. This chapter is about teaching your programs to think in well-cut pieces rather than giant monologues. 1. Top-Down Design: Breaking Big Problems into Friendly Pieces Top-down design is exactly what it sounds like: Start with the big idea. Then break it into smaller ideas. Then break those into even smaller ideas. It’s how architects design cities and how developers design real software. A Visual Snapshot  [MAIN PROBLEM]                  |    +--------+------+    |                       | [Task A]      [Task B...

🛡️ The Digital Compass: Integrity, Professionalism, and Ethics

 This blog post concludes your syllabus review with UNIT-V: Integrity and Professionalism , focusing on the essential lesson on ‘Professional Ethics’ . In an age dominated by digital tools, understanding your ethical responsibilities and mastering technical communication (report writing) is crucial for a successful and honorable career. 💼 Theme Focus: Professional Ethics in the Digital World Professional ethics are the moral principles that govern the conduct of a person or a group in a business or professional setting. In the digital age, these ethics are more critical than ever, especially concerning data, privacy, and intellectual property. Core Pillars of Professional Ethics: Integrity: Being honest and showing a consistent and uncompromising adherence to strong moral and ethical principles. Confidentiality: Protecting sensitive information (client data, company secrets). The digital world makes data vulnerable, making this pillar paramount. Responsibility: Taking ownership...

C Programming: The Quiet Architect Behind Modern Software

 Some programming languages arrive with fireworks. C arrived like a quiet architect who preferred blueprints over applause. Decades later, its designs still hold up half the digital world. From operating systems to embedded chips to performance-critical engines, the C language continues to whisper efficiency into the heart of modern computing. If you're stepping into programming for problem-solving, C isn't just a language to study — it's a foundation. A compass. A teacher with strict but rewarding lessons. Let’s take a walk through its essential elements, following the path laid out in classic texts like Hanly & Koffman, Forouzan & Gilberg, and, of course, the legendary K&R. 1. The DNA of C: Language Elements Every language has its alphabet. C has its own toolkit of tokens — the smallest meaningful units that build programs. These elements include: Keywords ( int , while , return , etc.) Identifiers (your variable and function names) Constants...