Peas in a Pod
Episode #4 of the course Getting started with C programming by Sudeshna Das
Hello!
I hope you’ve gotten the hang of using the different types of variables now.
Now what happens if we need to store ten integer values? The usual way would be to name all ten variables one by one, like so:
int a, b, c, d, e, f, g, h, i, j;
Reminds me of kindergarten, but doable. Now what if we had to store 100 integer values? Okay, now that’s a problem.
Arrays to the rescue!
An array is a group of variables of the same type. So, if we have an integer array of size 10, we could store 10 integers together without having to name each of them separately. We just need to name our array.
Let’s take an example:
#include<stdio.h>
void main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
printf(“%d %d %d %d”, a[1], a[2], a[4], a[7]);
}
http://codepad.org/pTBSKRCu
This program creates an integer array called a, which is of size 10. So, it has the capacity to store 10 integers. The values that we want to store are given inside curly braces, with commas separating them.
Did you notice something weird about the output? a[1] should ideally be displaying the first value in the array, but it is displaying the second value. Well, that is because in C, the arrays start from the index 0. So the first value—that is, 1—gets stored in a[0] and not a[1].
We can do everything with array elements that we would usually do with variables.
#include<stdio.h>
void main()
{
int a[5] = {1,4,3,2,2};
printf(“%d \n”, a[0]+a[1]);
printf(“%d”, a[4]+a[3]);
}
http://codepad.org/x24bmHWg
Here’s a simple program to add all the integers in an array and display the result:
#include<stdio.h>
void main()
{
int a[3] = {1001, 2002, 3003};
printf(“%d”, a[0]+a[1]+a[2]);
}
http://codepad.org/4RMO1yPX
Just like we have used an integer array, we can use float arrays and character arrays too.
#include<stdio.h>
void main()
{
char first_name[4] = {‘A’,’r’,’y’,’a’};
char last_name[5] = {‘S’,’t’,’a’,’r’,’k’};
printf(“Initials: %c.%c. \n”, first_name[0], last_name[0]);
printf(“First Name: %s \n”, first_name);
}
http://codepad.org/5iipaqEn
See the second printf? We have used %s to print a whole character array. This is what we call a string—as in, a string of characters.
We can do lots of fun stuff with strings, which is something that we will cover later in this course.
Tomorrow, we will learn about the most commonly used operators in C. Till then, keep coding!
Recommended book
“C Primer Plus” by Stephen Prata
Share with friends