0% found this document useful (0 votes)
5 views3 pages

C Programming Day7

Uploaded by

gogglezain
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)
5 views3 pages

C Programming Day7

Uploaded by

gogglezain
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

C Programming - Day 7: Arrays

What is an Array?
An array is a collection of variables of the same type stored at contiguous memory locations.

Why Use Arrays?


Instead of declaring multiple variables for the same purpose, we can use an array.
For example, instead of: int a1, a2, a3; we can write: int a[3];

Declaration and Initialization


Syntax:
int marks[5];
int marks[5] = {90, 85, 75, 60, 80};

Accessing Array Elements


Use index (starting from 0). Example:
printf("%d", marks[2]); // prints 3rd element

Example 1: Print elements of an array


int a[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("%d\n", a[i]);
}

Output:

10
20
30
40
50

Example 2: Calculate sum of elements


int a[5] = {10, 20, 30, 40, 50}, sum = 0;
for (int i = 0; i < 5; i++) {
sum += a[i];
}
printf("Sum = %d", sum);

Output:

Sum = 150
Example 3: Find maximum element
int a[5] = {10, 50, 30, 20, 40}, max = a[0];
for (int i = 1; i < 5; i++) {
if (a[i] > max)
max = a[i];
}
printf("Max = %d", max);

Output:

Max = 50

Example 4: Reverse an array


int a[5] = {1, 2, 3, 4, 5};
for (int i = 4; i >= 0; i--) {
printf("%d ", a[i]);
}

Output:

54321

Example 5: Count even numbers


int a[6] = {2, 5, 8, 11, 14, 17}, count = 0;
for (int i = 0; i < 6; i++) {
if (a[i] % 2 == 0)
count++;
}
printf("Even count = %d", count);

Output:

Even count = 3

Day 7 Summary:
Concept Description

Array Collection of same type elements

Indexing Starts from 0

Length Number of elements

Uses Loop through data, perform calculations

You might also like