Arrays and Structure In C

Introduction

Arrays and structure in C programming are powerful tools that help in storing, organizing, and managing data efficiently. Arrays allow the storage of multiple values of the same type using a single variable name, whether in one-dimensional, two-dimensional, or multi-dimensional forms. They are useful for performing operations like traversal, insertion, deletion, and searching. In addition to arrays, C provides structures, which are user-defined data types that group different data types together under one name—perfect for representing real-world entities like students, employees, or books. This unit also covers character and string handling, basic string functions, and introduces typedef and enum to simplify code and improve readability. Together, these concepts form the foundation for handling structured data in C programming.

This notes are provided by Study Shades Classes, Latur. (Prof. KAZI A. S. M.)

An array in C is a collection of similar data items, which have similar data type
and have a common name, is used to represent a group of related data items.
The data items can be integer, float or character. All data items must have
same data type and storage class. The first element in the array is numbered
0 and last element is one less than the size of array. Array is also known as
subscripted variable.

Array is of two types linear and non-linear.

1) Linear Array
One dimensional array is called linear array. They are represented by
using single sub script.
For E.g.:-int city [100];
City is the name of array. It can store 100 integer values.

Initialization of linear Array
Array can be initialized by giving initial values. These values must be
enclosed in brackets and separated by comma.
For e.g.:- int marks [5]={1,2,3,45};
Here marks are an array. It contains 5 values.

2) Non-linear array
Array having more than one sub script are called non-linear array. For
e.g.:- Two dimensional Arrays are non-linear array. 2D array have two
subscripts
Syntax: – int student [4] [2]

//program with a 2D array

#include <stdio.h>

int main() {
    int student[2][2]; // 2 students: [0]=roll no, [1]=marks
    int i, j;

    printf("Enter roll number and marks for 2 students:\n");

    for(i = 0; i < 2; i++) {
        printf("Student %d:\n", i + 1);
        for(j = 0; j < 2; j++) {
            if(j == 0)
                printf("  Roll No: ");
            else
                printf("  Marks: ");
            scanf("%d", &student[i][j]);
        }
    }

    printf("\nYou entered:\n");
    printf("Roll No\tMarks\n");

    for(i = 0; i < 2; i++) {
        for(j = 0; j < 2; j++) {
            printf("%d\t", student[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Input
Enter roll number and marks for 2 students:
Student 1:
Roll No: 101
Marks: 85
Student 2:
Roll No: 102
Marks: 90

Output
You entered:
Roll No Marks
101 85
102 90

Operations In Array

What are Array Operations?

Array operations are the basic tasks we perform to manage and use data stored in arrays. These operations include going through each element (traversal), adding new elements (insertion), removing elements (deletion), finding specific values (searching), and arranging data in a particular order (sorting). These operations help us to process and organize large sets of data efficiently. In C programming, array operations are performed using loops and sometimes built-in functions.

Traversal (Accessing all elements)

Description: Visiting and printing each element in the array using a loop.

#include <stdio.h>
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:- 10 20 30 40 50

Insertion (Adding an element)

Description: Inserting a new value at a specific position by shifting elements.

#include <stdio.h>
int main() {
    int arr[6] = {10, 20, 30, 40, 50};
    int pos = 2, value = 25;  // Insert at index 2
    for (int i = 5; i > pos; i--) {
        arr[i] = arr[i - 1];
    }
    arr[pos] = value;
    for (int i = 0; i < 6; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:- 10 20 25 30 40 50

Deletion (Removing an element)

Description: Deleting an element from a given position by shifting the rest left.

#include <stdio.h>
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int pos = 2;  // Delete element at index 2
    for (int i = pos; i < 4; i++) {
        arr[i] = arr[i + 1];
    }
    for (int i = 0; i < 4; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:- 10 20 40 50

Character and String I/O and Basic String Functions

Difference between Character and String

In C programming, a character is a single symbol like 'A', 'b', or '1' and is stored in a char type variable. A string is a group of characters stored in a character array and always ends with a special null character '\0' to indicate the end of the string.
Example:
char ch = ‘A’; // Single character
char str[] = “Hello”; // String (character array)

Using scanf() and printf()

The scanf() function in C is used to take input from the user through the keyboard. For reading a single character, we use %c, and for reading strings (without spaces), we use %s.

The printf() function is used to display output on the screen—this includes characters, strings, and other data types like integers or floats. While using scanf() with %s, it stops reading when it encounters a space, so it is only suitable for single-word inputs. For example, if you input “Hello World”, only “Hello” will be stored in the string.

Using gets() and puts()

The gets() function is used to read a full line of text, including spaces, and stores it in a character array. This was helpful when users needed to enter full names or sentences. However, gets() is considered unsafe because it does not check the size of the array, which can lead to memory overflow or crashes if more characters are entered than expected.

The puts() function is used to display a string on the screen and automatically adds a new line at the end. It is simple to use and safer than printf() for strings when no formatting is required.

Basic String Functions

1.strlen()
The strlen() function is used to find the length of a string, excluding the null character \0. It counts the number of characters in the string until it reaches the end. This function is useful for checking string size before operations like copying or joining.

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

int main() {
    char str[] = "Hello";
    printf("Length: %lu", strlen(str));
    return 0;
}

Output: Length: 5

2.strcpy()
The strcpy() function is used to copy one string into another. The destination string must be large enough to hold the copied data. After copying, both strings will have the same content.

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

int main() {
    char src[] = "World";
    char dest[10];
    strcpy(dest, src);
    printf("Copied String: %s", dest);
    return 0;
}

Output: Copied String: World

3.strcat()
The strcat() function is used to join two strings. It adds the second string to the end of the first one (concatenation). Make sure the first string has enough space to store the combined result.

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

int main() {
    char str1[20] = "Good ";
    char str2[] = "Morning";
    strcat(str1, str2);
    printf("Result: %s", str1);
    return 0;
}

Output: Result: Good Morning

4.strcmp()
The strcmp() function is used to compare two strings. It returns 0 if the strings are equal, a negative value if the first is smaller, and a positive value if the first is greater. It’s case-sensitive.

Structures In C

1.What is a Structure?
In C programming, a structure is a user-defined data type that allows you to group variables of different data types under a single name. It is defined using the struct keyword. Each variable inside a structure is called a member, and they can be of different types like int, float, char, etc. Structures help organize related data together—for example, a student’s name, roll number, and marks can be grouped in one structure. Unlike arrays (which store similar data types), structures store different types of information. They are very useful when dealing with complex data in real-world programs.

2.Features of Structures
Structures allow you to store multiple data types (like int, float, char) in a single unit, which is not possible with arrays. This makes them ideal for representing real-world entities like students, employees, or books. Structures help make the code more organized and easier to manage. They are commonly used in database applications and system programming.

3.How to Declare a Structure
In C, a structure is declared using the struct keyword followed by the structure name and its member variables inside curly braces {}. The declaration does not allocate memory; it only creates a template or blueprint. Memory is allocated only when we create a variable of the structure type.

Syntax
struct StructureName
{
data_type member1;
data_type member2;

};

Example: Declaring a Student Structure

#include <stdio.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

In this example:

  • Student is the name of the structure.
  • It has three members: roll (integer), name (string/character array), and marks (float).
  • This structure can now be used to create variables that store information about students.

4.Accessing Members
To access individual members of a structure, we use the dot (.) operator along with the structure variable name. This allows us to read or update specific values stored in the structure. It is similar to accessing elements in an object or a record.
Example

#include <stdio.h>

struct Student {
    int roll;
    char name[20];
    float marks;
};

int main() {
    struct Student s1 = {1, "Rahul", 75.5};
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);
    return 0;
}

Output
Name: Rahul
Marks: 75.50

5.Array of Structures
An array of structures is used to store and manage multiple records of the same type, like a list of students. You can access each record using an index and then use the dot operator to access individual fields.
Example

#include <stdio.h>

struct Student {
    int roll;
    char name[20];
    float marks;
};

int main() {
    struct Student s[2] = {
        {1, "Anjali", 80.5},
        {2, "Vikram", 72.0}
    };

    for (int i = 0; i < 2; i++) {
        printf("Roll: %d, Name: %s, Marks: %.1f\n", s[i].roll, s[i].name, s[i].marks);
    }

    return 0;
}

Output
Roll: 1, Name: Anjali, Marks: 80.5
Roll: 2, Name: Vikram, Marks: 72.0

typedef and Enumerated Data Type (enum)

1.What is typedef?

In C, typedef is a keyword used to create a new name (alias) for an existing data type. This makes the code easier to read and maintain, especially when using long or complex type definitions. It is commonly used to simplify types like unsigned int, structures, or even pointers.

Using typedef doesn’t create a new data type; it just gives a new name to an existing one.

#include <stdio.h>

typedef int myInt;  // 'myInt' is now an alias for 'int'

int main() {
    myInt x = 10;   // Same as: int x = 10;
    printf("Value: %d", x);
    return 0;
}

Output: Value: 10

You can also use typedef with structures.

typedef struct {
    int id;
    char name[20];
} Student;

Student s1 = {1, "Rahul"};

Now, instead of writing struct Student, you can simply use Student.

2.What is enum (Enumerated Data Type)?

An enumeration (or enum) is a user-defined type that consists of a set of named integer constants. It is mainly used to assign meaningful names to numbers, making the code more readable. By default, the values start from 0 and increase by 1, unless specified otherwise.

It’s very useful when you have a fixed set of values—like days of the week, months, menu choices, etc.

Simple Syntax:
enum Day {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

By default: – sun=0 mon=1 tue=2 and so on.

You can also assign custom values:
enum Status {Pending = 1, Approved = 5, Rejected = 10};

Example

#include <stdio.h>

enum Day {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

int main() {
    enum Day today = Tue;
    printf("Day number: %d", today);
    return 0;
}

Output: Day number: 2

Conclusion

In this unit, we learned about arrays and structures—two important tools in C programming for handling data efficiently. Arrays help store and manage multiple values of the same type using one-dimensional, two-dimensional, or even multi-dimensional forms. We also explored how to declare and initialize arrays, and perform operations like traversal, insertion, deletion, and searching.

Character and string handling was introduced, along with basic string functions like strlen(), strcpy(), strcat(), and strcmp(). We then moved on to structures, which allow grouping of different data types together—useful in real-world applications. Finally, we learned about typedef for creating type aliases and enum for defining named constants, which improve code clarity and readability.

Together, these concepts build a strong foundation for working with data in C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top