0% found this document useful (0 votes)
4 views22 pages

Bba C Programming Notes Unit-4

This document provides an overview of arrays and structures in C programming, detailing their definitions, types, and usage. It covers array declaration, initialization, and memory representation, along with standard string library functions and the concept of structures, including nested structures and unions. The document includes examples and syntax to illustrate how to work with these data types effectively.

Uploaded by

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

Bba C Programming Notes Unit-4

This document provides an overview of arrays and structures in C programming, detailing their definitions, types, and usage. It covers array declaration, initialization, and memory representation, along with standard string library functions and the concept of structures, including nested structures and unions. The document includes examples and syntax to illustrate how to work with these data types effectively.

Uploaded by

bhumala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SEMESTER: II

BBA-OE-124 Basics of C Programming


------------------------------------------------------------------------------------
UNIT-IV ARRARY AND STRUCTURE
Arrays:-
An array is a collection of items of the same variable type that are stored at contiguous memory
locations. It is one of the most popular and simple data structures used in programming.

Basic terminologies of Array

 Array Element: Elements are items stored in an array.

 Array Index: Elements are accessed by their indexes. Indexes in most of the programming
languages start from 0.

Memory representation of Array

In an array, all the elements or their references are stored in contiguous memory locations. This allows
for efficient access and manipulation of elements.

Array declaration, initialization:-


Declaration of Array
Arrays can be declared in various ways in different languages. For better illustration, below are some
language-specific array declarations:

// This array will store integer type element

int arr[5];

// This array will store char type element

char arr[10];

// This array will store float type element

float arr[20];

Initialization of Array

Arrays can be initialized in different ways in different languages. Below are some language-specific array
initialization:

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

char arr[5] = { 'a', 'b', 'c', 'd', 'e' };

float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };

Why do we Need Arrays?

Assume there is a class of five students and if we have to keep records of their marks in examination
then, we can do this by declaring five variables individual and keeping track of records but what if the
number of students becomes very large, it would be challenging to manipulate and maintain the data.
So we use an array of students.
Types of Arrays

Arrays can be classified in two ways:

 On the basis of Size

 On the basis of Dimensions

Types of Arrays on the basis of Size

1. Fixed Sized Arrays

 We cannot alter or update the size of this array. Here only a fixed size (i,e. the size that is
mentioned in square brackets []) of memory will be allocated for storage.

 In case, we don't know the size of the array then if we declare a larger size and store a lesser
number of elements, it will result in a wastage of memory. And if we declare a lesser size than
the number of elements then we won't get enough memory to store all the elements.

// Method 1 to create a fixed sized array.

// Here the memory is allocated at compile time.

int arr[5];

// Another way (creation and initialization both)


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

// Method 2 to create a fixed sized array

// Here memory is allocated at run time (Also

// known as dynamically allocated arrays)

int *arr = new int[5];

2. Dynamic Sized Arrays

The size of the array changes as per user requirements during execution of code so the coders do not
have to worry about sizes. They can add and removed the elements as per the need. The memory is
mostly dynamically allocated and de-allocated in these arrays.

#include<vector>

// Dynamic Integer Array

vector<int> v;

Types of Arrays on the basis of Dimensions

1. One-dimensional Array(1-D Array): You can imagine a 1d array as a row, where elements are stored
one after another.
2. Multi-dimensional Array: A multi-dimensional array is an array with more than one dimension. We
can use multidimensional array to store complex data in the form of tables, etc. We can have 2-D arrays,
3-D arrays, 4-D arrays and so on.

 Two-Dimensional Array(2-D Array or Matrix): 2-D Multidimensional arrays can be considered as


an array of arrays or as a matrix consisting of rows and columns.

To read more about Matrix Refer, Matrix Data Structure

Standard String library functions:-

Standard String Library Functions in C (<string.h>)

1️⃣ String Length – strlen()

Theory:
strlen() returns the number of characters in a string excluding the null character '\0'.
Syntax:

size_t strlen(const char *str);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello";

printf("Length of '%s' is %lu\n", str, strlen(str));

return 0;

Output:

Length of 'Hello' is 5

2️⃣ String Copy – strcpy() and strncpy()

Theory:

 strcpy(dest, src) copies the whole string src into dest.

 strncpy(dest, src, n) copies at most n characters (useful for buffer safety).

Syntax:

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

char *strncpy(char *dest, const char *src, size_t n);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char src[] = "Hello";

char dest[10];

strcpy(dest, src);
printf("Copied string: %s\n", dest);

return 0;

Output:

Copied string: Hello

3️⃣ String Concatenation – strcat() and strncat()

Theory:

 strcat(dest, src) appends src to the end of dest.

 strncat(dest, src, n) appends at most n characters.

Syntax:

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

char *strncat(char *dest, const char *src, size_t n);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str1[20] = "Hello, ";

char str2[] = "World!";

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

return 0;

Output:

Concatenated string: Hello, World!

4️⃣ String Comparison – strcmp() and strncmp()

Theory:
 strcmp(str1, str2) compares two strings.

 Returns 0 if equal, negative if str1 < str2, positive if str1 > str2.

 strncmp() compares only the first n characters.

Syntax:

int strcmp(const char *str1, const char *str2);

int strncmp(const char *str1, const char *str2, size_t n);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "Apple";

char str2[] = "Banana";

int result = strcmp(str1, str2);

if (result == 0)

printf("Strings are equal\n");

else if (result < 0)

printf("str1 is less than str2\n");

else

printf("str1 is greater than str2\n");

return 0;

Output:

str1 is less than str2

5️⃣ String Searching – strchr(), strrchr(), strstr()

Theory:

 strchr(str, ch) → finds first occurrence of character ch.

 strrchr(str, ch) → finds last occurrence.


 strstr(str, substr) → finds substring in string.

Syntax:

char *strchr(const char *str, int ch);

char *strrchr(const char *str, int ch);

char *strstr(const char *str, const char *substr);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello World";

printf("First 'o' at: %s\n", strchr(str, 'o'));

printf("Last 'o' at: %s\n", strrchr(str, 'o'));

printf("Substring 'World' found at: %s\n", strstr(str, "World"));

return 0;

Output:

First 'o' at: o World

Last 'o' at: orld

Substring 'World' found at: World

6️⃣ String Tokenizing – strtok()

Theory:
strtok() splits a string into tokens based on delimiters.

Syntax:

char *strtok(char *str, const char *delim);

Example:

#include <stdio.h>

#include <string.h>
int main() {

char str[] = "C,Python,Java";

char *token = strtok(str, ",");

while (token != NULL) {

printf("%s\n", token);

token = strtok(NULL, ",");

return 0;

Output:

Python

Java

7️⃣ Memory Functions – memcpy(), memmove(), memset(), memcmp()

Theory:

 memcpy(dest, src, n) → copy n bytes.

 memmove(dest, src, n) → copy n bytes safely if regions overlap.

 memset(ptr, val, n) → fill memory with value.

 memcmp(ptr1, ptr2, n) → compare memory.

Example (memset):

#include <stdio.h>

#include <string.h>

int main() {

char str[10];

memset(str, '*', 5);

str[5] = '\0';
printf("String after memset: %s\n", str);

return 0;

Output:

String after memset: *****

Creating structures:-
1️⃣ What is a Structure?

Theory:
A structure in C is a user-defined data type that allows you to group variables of different data types
together under a single name.

 Think of it like a record.

 Example: A student record contains name (string), age (int), and marks (float).

 Structures help organize complex data in a clean way.

2️⃣ Syntax of a Structure

struct StructureName {

data_type member1;

data_type member2;

...

};

 StructureName → name of the structure.

 member1, member2 → variables of possibly different types.

Example: Define a Student Structure

#include <stdio.h>
struct Student {

char name[50];

int age;

float marks;

};

Here, we defined a structure named Student with three members: name, age, and marks.

3️⃣ Declaring Structure Variables

You can declare structure variables in 3 ways:

1. After structure definition:

struct Student s1, s2;

2. Inside structure definition:

struct Student {

char name[50];

int age;

float marks;

} s1, s2;

3. Using typedef (avoids writing struct every time):

typedef struct {

char name[50];

int age;

float marks;

} Student;

Student s1, s2; // no need for 'struct' keyword

4️⃣ Accessing Structure Members

 Use the dot operator (.) for normal structure variables.

 Use the arrow operator (->) for structure pointers.


[Link] = 20; // dot operator

printf("%d", [Link]);

struct Student *ptr = &s1;

ptr->age = 21; // arrow operator

printf("%d", ptr->age);

5️⃣ Example: Using a Structure

#include <stdio.h>

#include <string.h>

struct Student {

char name[50];

int age;

float marks;

};

int main() {

struct Student s1;

// Assign values

strcpy([Link], "Alice");

[Link] = 20;

[Link] = 88.5;

// Print values

printf("Name: %s\n", [Link]);

printf("Age: %d\n", [Link]);

printf("Marks: %.2f\n", [Link]);


return 0;

Output:

Name: Alice

Age: 20

Marks: 88.50

Explanation:

 strcpy is used to copy strings to the name member.

 Dot operator (.) is used to access age and marks.

6️⃣ Nested Structures

You can define a structure inside another structure.

#include <stdio.h>

struct Date {

int day, month, year;

};

struct Student {

char name[50];

int age;

struct Date dob; // nested structure

};

int main() {

struct Student s1;

[Link] = 20;

strcpy([Link], "Bob");
[Link] = 5;

[Link] = 6;

[Link] = 2003;

printf("Name: %s\n", [Link]);

printf("DOB: %d-%d-%d\n", [Link], [Link], [Link]);

return 0;

Output:

Name: Bob

DOB: 5-6-2003

Explanation:

 The dob member is itself a structure Date.

 Access nested members with . operator like [Link].

7️⃣ Array of Structures

You can store multiple records using arrays of structures.

#include <stdio.h>

#include <string.h>

struct Student {

char name[50];

int age;

float marks;

};

int main() {

struct Student students[3];


strcpy(students[0].name, "Alice");

students[0].age = 20;

students[0].marks = 85;

strcpy(students[1].name, "Bob");

students[1].age = 21;

students[1].marks = 90;

strcpy(students[2].name, "Charlie");

students[2].age = 19;

students[2].marks = 95;

for(int i=0; i<3; i++){

printf("%s, Age: %d, Marks: %.2f\n", students[i].name, students[i].age, students[i].marks);

return 0;

Output:

Alice, Age: 20, Marks: 85.00

Bob, Age: 21, Marks: 90.00

Charlie, Age: 19, Marks: 95.00

Explanation:

 Each element of the array students[] is a separate Student record.

 Loop through the array to access and print each student’s details.

8️⃣ Pointers to Structures

 Use pointers to access structure members with -> operator.


struct Student s1;

struct Student *ptr = &s1;

strcpy(ptr->name, "Alice");

ptr->age = 20;

printf("Name: %s, Age: %d\n", ptr->name, ptr->age);

Output:

Name: Alice, Age: 20

Explanation:

 ptr points to s1.

 -> operator is used to access members through the pointer.

Unions in C:-

1️⃣ What is a Union?

Theory:
A union is a user-defined data type in C, similar to a structure, but with one key difference:

 All members of a union share the same memory location.

 At any given time, a union can store a value in only one of its members.

 Memory allocated for a union is equal to the size of its largest member.

Use case:
Unions are useful when you need to store different types of data in the same memory location, but not
at the same time.

2️⃣ Syntax of Union

union UnionName {

data_type member1;
data_type member2;

...

};

 UnionName → name of the union.

 member1, member2 → variables of possibly different types.

3️⃣ Example 1: Basic Union

#include <stdio.h>

#include <string.h>

// Define a union

union Data {

int i;

float f;

char str[20];

};

int main() {

union Data data;

data.i = 10;

printf("data.i = %d\n", data.i);

data.f = 220.5;

printf("data.f = %.2f\n", data.f);

strcpy([Link], "Hello");

printf("[Link] = %s\n", [Link]);


printf("After storing string, data.i = %d\n", data.i); // previous value overwritten

return 0;

Output:

data.i = 10

data.f = 220.50

[Link] = Hello

After storing string, data.i = 0 (or garbage)

Explanation:

 Initially data.i = 10.

 Then data.f = 220.5 overwrites the same memory, so data.i is lost.

 When we store a string, it overwrites again.

 Only one member can hold a value at a time.

4️⃣ Size of a Union

Theory:

 Size of a union = size of its largest member.

 Example:

#include <stdio.h>

union Data {

int i; // 4 bytes

float f; // 4 bytes

char str[20]; // 20 bytes

};

int main() {

printf("Size of union: %lu\n", sizeof(union Data));


return 0;

Output:

Size of union: 20

Explanation:

 Memory is shared, so the union only needs enough space for the largest member, which is char
str[20].

5️⃣ Accessing Union Members

 Use dot operator (.) for normal variables.

 Use arrow operator (->) for pointers.

union Data data;

data.i = 50;

printf("%d\n", data.i);

6️⃣ Example 2: Using Union with Struct

Unions can be used inside structures for memory optimization.

#include <stdio.h>

#include <string.h>

struct Employee {

char name[50];

int type; // 1 = hourly, 2 = salaried

union {

float hourly_rate;

float salary;

} pay;

};
int main() {

struct Employee emp;

strcpy([Link], "Alice");

[Link] = 1; // hourly employee

[Link].hourly_rate = 50.0;

printf("Name: %s\n", [Link]);

if([Link] == 1)

printf("Hourly Rate: %.2f\n", [Link].hourly_rate);

else

printf("Salary: %.2f\n", [Link]);

return 0;

Output:

Name: Alice

Hourly Rate: 50.00

Explanation:

 The pay union holds either hourly_rate or salary, depending on employee type.

 Saves memory compared to using separate members for both.

7️⃣ Key Differences Between Union and Structure

Feature Structure Union

Memory Each member has separate memory All members share same memory

Size Sum of sizes of all members Size of largest member

Members Access Can access all members simultaneously Only one member at a time

Use Case Store all data together Store different types one at a time

You might also like