0% found this document useful (0 votes)
10 views

Lecture Six

Uploaded by

alvinmwangisir
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)
10 views

Lecture Six

Uploaded by

alvinmwangisir
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
You are on page 1/ 14

UNIVERSITY OF EMBU

SCHOOL OF PURE AND APPLIED SCIENCES


DEPARTMENT OF MATHEMATICS, COMPUTING & IT

STA 121: PROGRAMMING METHODOLOGY

WRITTEN BY: EDITED BY:


MR JOHN KIRWA

Copyright © UNIVERSITY OF EMBU, AUGUST 2020


All Rights Reserved
LESSON 6: ARRAYS

An array is a collection of data elements of the same data type. It is described by a single name
and each element of an array is referenced by using the array name and its index number.

Declaration of Array

Type arrayName[numberOfElements];

For example,

int Age[5] ;
float cost[30];

Initialization of One-Dimensional Array

An array can be initialized along with the declaration. For array initialization, it is required to
place the elements separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};

It is possible to leave the array size open. The compiler will count the array size.
int B[] = {6,7,8,9,15,12};

Referring to Array Elements

In any point of a program in which an array is visible, we can access the value of any of its
elements individually as if it was a normal variable, thus being able to both read and modify its
value. The format is as simple as:
name[index]

Examples:
printf("%d", age[4]); /* print an array element */
age[4] = 55; /* assign value to an array element */
scanf("%d", &age[4]); /* input element */

Using Loop to input an Array from user


int age [10], i ;
for (i=0 ; i<10; i++)
{
scanf("%d", &age[i]);
}

Arrays as Parameters

At some moment we may need to pass an array to a function as a parameter. In C it is not


possible to pass a complete block of memory by value as a parameter to a function, but we are
allowed to pass its address.
For example, the following function:
void print(int A[])
accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:
int arr[20];
we need to write a call like this:
print(arr);

Here is a complete example:

/* This program illustrates array as function parameter */

#include <stdio.h>

void print(int[], int);


int main()
{
int arr[] = {5, 10, 15};
print(arr, 3);
return 0;
}
void print(int A[], int length)
{
int i;
for (i = 0; i < length; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
Output:
5 10 15

Two-Dimensional Array

It is a collection of data elements of the same data type arranged in rows and columns (that is, in
two dimensions).

Declaration of Two-Dimensional Array

Type arrayName[numberOfRows][numberOfColumns];

For example,
int Sales[3][5];

Initialization of Two-Dimensional Array

A two-dimensional array can be initialized along with the declaration. For two-dimensional array
initialization, elements of each row are enclosed within curly braces and separated by commas.
All rows are enclosed within curly braces.
int A[4][3] = {{22, 23, 10},
{15, 25, 13},
{20, 74, 67},
{11, 18, 14}};

Referring to Array Elements

To access the elements of a two-dimensional array, we need a pair of indices: one for the row
position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]
Examples:
printf("%d", A[1][2]); /* print an array element */
A[1][2]=13; /* assign value to an array element */
scanf("%d", &A[1][2]); /* input element */

Using Loop to input a Two-Dimensional Array from user

int A[3][5], i, j ;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &A[i][j];
}
}

Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by
reference. When declaring a two-dimensional array as a formal parameter, we can omit the size
of the first dimension, but not the second; that is, we must specify the number of columns. For
example:
void print(int A[][3],int n, int m)
In order to pass to this function an array declared as:
int arr[4][3];
we need to write a call like this:
print(arr);

Here is a complete example:

#include <stdio.h>

void input(int matrix[][10], int, int);


void display(int matrix[][10], int, int);
int main()
{
int r, c;

int A[10][10];

printf("Enter number of rows: ");


scanf("%d", &r);

printf("Enter number of columns: ");


scanf("%d", &c);

input(A, r, c);
printf("\n");
display(A, r, c);

return 0;
}

void input(int matrix[][10], int m, int n)


{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("Enter data in [%d][%d] : ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}

void display(int matrix[][10], int m, int n)


{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
Output:
Enter the number of rows: 3
Enter the number of columns: 4
Enter data in [0][0] : 10
Enter data in [0][1] : 11
Enter data in [0][2] : 12
Enter data in [0][3] : 13
Enter data in [1][0] : 18
Enter data in [1][1] : 19
Enter data in [1][2] : 40
Enter data in [1][3] : 35
Enter data in [2][0] : 33
Enter data in [2][1] : 25
Enter data in [2][2] : 16
Enter data in [2][3] : 56

10 11 12 13
18 19 40 35
33 25 16 56

Strings (Character Arrays)

STRING: It is an array of type char.

Syntax for declaration


char <array/string name> [max. number of characters to be stored +1];
The number of elements that can be stored in a string is always n-1 if the size of the array
specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero.
A string is always terminated with the NULL character.
Example:
char str[80];
In the above example, str can be used to store a string with 79 characters.

Initializing a string
A string can be initialized to a constant value when it is declared.
char str[ ] = "Good";
Or
char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1], and so on.
Note: When the value is assigned to the complete string at once, the computer automatically
inserts the NULL character at the end of the string. But, if it is done character by character, then
we have to insert it at the end of the string.
Reading strings with/without embedded blanks
To read a string without blanks scanf can be used
scanf("%s", str);
To read a string with blanks gets() can be used.
gets(str);

Printing strings
printf() and puts() can be used to print a string.
printf("%s", str);
Or
puts(str);

String Library Functions


The string-handling library (<string.h>) provides many useful functions for manipulating string
data
strlen(s) Determines the length of string s.

compares its first string argument to its second string argument, character by
character. It returns 0 if the strings are equal, returns a negative value if the first
strcmp(s1,s2)
string is less than the second, and returns a positive value if the first string is
greater than the second.

strcpy(s1,s2) Copies string s2 into array s1. The value of s1 is returned.

Appends string s2 to array s1. The first character of s2 overwrites the terminating
strcat()
null character of s1. The value of s1 is returned.

Locates the first occurrence in string s1 of string s2. If the string is found, a pointer
strstr()
to the string in s1 is returned. Otherwise, a NULL pointer is returned.

Structure

A structure is a collection of variable which can be the same or different types. You can refer to a
structure as a single variable, and its parts as members of that variable by using the dot (.)
operator. The power of structures lies in the fact that once defined, the structure name becomes
a user-defined data type and may be used the same way as other built-in data types, such as int,
double, char.
struct Student
{
int rollno, age;
char name[80];
float marks;
};

int main()
{

/* declare two variables of the new type */


struct Student s1, s3;

/* accessing of data members */


scanf("%d%d%s%f", &s1.rollno, &s1.age, s1.name, &s1.marks);
printf("%d %d %s %f", s1.rollno, s1.age, s1.name, s1.marks);

/* initialization of structure variable */


struct Student s2 = {100, 17, "Aniket", 92};
printf("%d %d %s %f", s2.rollno, s2.age, s2.name, s2.marks);

/* structure variable in assignment statement */


s3 = s2;
printf("%d %d %s %f", s3.rollno, s3.age, s3.name, s3.marks);

return 0;
}

Defining a structure
When dealing with the students in a school, many variables of different types are needed. It may
be necessary to keep track of name, age, Rollno, and marks the point for example.
struct Student
{
int rollno, age;
char name[80];
float marks;
};

The student is called the structure tag and is your brand new data type, like int, double, or char.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct


The most efficient method of dealing with structure variables is to define the structure globally.
This tells "the whole world", namely main and any functions in the program, that a new data type
exists. To declare a structure globally, place it BEFORE void main(). The structure variables
can then be defined locally in main, for example…
Declaring global variables of type struct:

struct Student
{
int rollno, age;
char name[80];
float marks;
} s1, s3;

Declaring structure variables inside main of type struct:

struct Student
{
int rollno, age;
char name[80];
float marks;
};

int main()
{
/* declare two variables of the new type */
struct Student s1, s3;
………
………
return 0;
}

Accessing of data members


The accessing of data members is done by using the following format:
structure variable.member name
for example

scanf("%d%d%s%f", &s1.rollno, &s1.age, s1.name, &s1.marks);

Initialization of structure variable


Initialization is done at the time of declaration of a variable. For example

struct Student s2 = {100, 17, "Aniket", 92};

Structure variable in assignment statement

s3 = s2;

The statement assigns the value of each member of s2 to the corresponding member of s3. Note
that one structure variable can be assigned to another only when they are of the same structure
type, otherwise the compiler will give an error.

Nested structure (Structure within a structure)


It is possible to use a structure to define another structure. This is called nesting of structure.
Consider the following program

struct Day
{
int month, date, year;
};

struct Student
{
int rollno, age;
char name[80];
struct Day date_of_birth;
float marks;
};

Accessing Member variables of Student


To access members of date_of_birth we can write the statements as below :

struct Student s; // Structure variable of Student

s.date_of_birth.month = 11;
s.date_of_birth.date = 5;
s.date_of_birth.year = 1999;

Arrays of Structure
To store data of 20 students we would be required to use 20 different structure variables from s1
to s20, which is not very convenient. A better approach would be to use an array of structures.
The following program shows how to use an array of structures.

#include <stdio.h>

struct student
{
int rollno;
char name[80];
int marks;
};

void accept(struct student[], int);


void display(struct student[], int);

int main()
{
struct student data[20];
int n, choice, rollno;

printf("Number of records you want to enter? : ");


scanf("%d", &n);
accept(data, n);
display(data, n);

return 0;
}

void accept(struct student list[80], int s)


{
int i;
for (i = 0; i < s; i++)
{
printf("\nEnter data for Record #%d", i + 1);

printf("\nEnter rollno : ");


scanf("%d", &list[i].rollno);
fflush(stdin);
printf("Enter name : ");
gets(list[i].name);

printf("Enter marks : ");


scanf("%d", &list[i].marks);
}
}

void display(struct student list[80], int s)


{
int i;

printf("\n\nRollno\tName\tMarks\n");
for (i = 0; i < s; i++)
{
printf("%d\t%s\t%d\n", list[i].rollno, list[i].name, list[i].marks);
}
}

Output:
Number of records you want to enter? : 3

Enter data for Record #1


Enter rollno: 100
Enter name: Krishna
Enter marks: 95

Enter data for Record #2


Enter rollno: 101
Enter name: Alex
Enter marks: 85

Enter data for Record #3


Enter rollno: 102
Enter name: Javed
Enter marks: 90

Rollno Name Marks


100 Krishna 95
101 Alex 85
102 Javed 90
Pointer in C

Accessing the address of a variable


The computer’s memory is organized as a linear collection of bytes. Every byte in the
computer’s memory has an address. Each variable in the program is stored at a unique address.
We can use the address operator & to get the address of a variable:
int num = 23;
printf("%d", &num); /* prints address of num */

Related links

The development of C language by Dennis M. Ritchie

DJGPP a complete 32-bit C/C++ development system for Intel 80386 and higher PCs.

List of Free C Compilers and interpreters available on the internet.

https://www.sanfoundry.com/c-programming-examples/

You might also like