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

Lec-06 spl-c-array-06

The document provides an overview of arrays in C programming, including their definition, declaration, initialization, and types such as character and multidimensional arrays. It includes examples of using arrays to perform tasks like summing even integers, counting survey responses, generating Fibonacci numbers, and identifying prime numbers. Additionally, it covers the concept of initializing arrays and processing matrix elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lec-06 spl-c-array-06

The document provides an overview of arrays in C programming, including their definition, declaration, initialization, and types such as character and multidimensional arrays. It includes examples of using arrays to perform tasks like summing even integers, counting survey responses, generating Fibonacci numbers, and identifying prime numbers. Additionally, it covers the concept of initializing arrays and processing matrix elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Outline

• Arrays
o The concept of array
o Defining arrays
o Initializing arrays
o Character arrays
o Multidimensional arrays
o Variable length arrays
The concept of array
• Array: a set of ordered data items
• You can define a variable called x, which represents
not a single value, but an entire set of values.
• Each element of the set can then be referenced by
means of a number called an index number or
subscript.
• Mathematics: a subscripted variable, xi, refers to the
ith element x in a set
• C programming: the equivalent notation is x[i]
Declaring an array
• Declaring an array variable:
o Declaring the type of elements that will be contained in the
array—such as int, float, char, etc.
o Declaring the maximum number of elements that will be
stored inside the array.
• The C compiler needs this information to determine how much
memory space to reserve for the array.)
• This must be a constant integer value
• The range for valid index values in C:
o First element is at index 0
o Last element is at index [size-1]
o It is the task of the programmer to make sure that array
elements are referred by indexes that are in the valid range !
The compiler cannot verify this, and it comes to severe
runtime errors !
Arrays - Example
Example:
int values[10];
Declares an array of 10 elements of type int
Using Symbolic Constants for array size:
#define N 10

int values[N];

Valid indexes:
values[0]=5;
values[9]=7;
Invalid indexes:
values[10]=3;
values[-1]=6;
In memory: elements of an array are stored
at consecutive locations
Arrays - Example
#include <stdio.h> Using symbolic
#define N 6 constants for array
int main (void) size makes program
{ more general
int values[N];
int index;
for ( index = 0; index < N; ++index ) {
printf(“Enter value of element #%i \n”,index);
scanf(“%i”, &values[index]);
}
for ( index = 0; index < N; ++index )
printf("values[%i]= %i\n",index, values[index]);
return 0;
}
Typical loop for
processing all
elements of an array
Class Room Practice

WAP that will take n integer numbers into an array, and then
sum up all the even integers in that array.

Sample input Sample output


5 6
1 2 3 4 5
6 10
2 8 3 9 0 1

6-Jul-22 7
Exercise
• Suppose you took a survey to discover how people felt
about a particular television show and you asked each
respondent to rate the show on a scale from 1 to 10,
inclusive. After interviewing 5,000 people, you
accumulated a list of 5,000 numbers. Now, you want to
analyze the results.
• One of the first pieces of data you want to gather is a
table showing the distribution of the ratings: you want to
know how many people rated the show a 1, how many
rated it a 2, and so on up to 10.
• Develop a program to count the number of responses
for each rating.
Exercise: Array of counters
response

ratingCounters

++

0 1 2 9 10

ratingCounters[i] = how many persons rated the show an i


Exercise: Array of counters
#include <stdio.h>
int main (void) {
int ratingCounters[11], i, response;
for ( i = 1; i <= 10; ++i )
ratingCounters[i] = 0;
printf ("Enter your responses\n");
for ( i = 1; i <= 20; ++i ) {
scanf ("%i", &response);
if ( response < 1 || response > 10 )
printf ("Bad response: %i\n", response);
else
++ratingCounters[response];
}
printf ("\n\nRating Number of Responses\n");
printf ("------ -------------------\n");
for ( i = 1; i <= 10; ++i )
printf ("%4i%14i\n", i, ratingCounters[i]);
return 0;
}
Exercise: Fibonacci numbers
// Program to generate the first 15 Fibonacci numbers
#include <stdio.h>
int main (void)
{
int Fibonacci[15], i;
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < 15; ++i )
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < 15; ++i )
printf ("%i\n", Fibonacci[i]);
return 0;
}
Difficult Exercise: Prime numbers
• An improved method for generating prime numbers involves the notion
that a number p is prime if it is not evenly divisible by any other prime
number
• Another improvement: a number p is prime if there is no prime number
smaller than its square root, so that it is evenly divisible by it

If you can find a


Is p the next
primes[i] < sqrt(p)
prime number
that divides evenly
here ?
p, than p is not
prime
primes

2 3 5 7 11

0 1 2

primeIndex
Exercise: Prime numbers
#include <stdio.h>
#include <stdbool.h>
// Modified program to generate prime numbers
int main (void) {
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for ( p = 5; p <= 50; p = p + 2 ) {
isPrime = true;
for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i )
if ( p % primes[i] == 0 )
isPrime = false;
if ( isPrime == true ) {
primes[primeIndex] = p;
++primeIndex;
}
}
for ( i = 0; i < primeIndex; ++i )
printf ("%i ", primes[i]);
printf ("\n");
return 0;
}
Initializing arrays
int counters[5] = { 0, 0, 0, 0, 0 };
char letters[5] = { 'a', 'b', 'c', 'd', 'e' };
float sample_data[500] = { 100.0, 300.0, 500.5 };

• The C language allows you to define an array without specifying


the number of elements. If this is done, the size of the array is
determined automatically based on the number of initialization
elements:
int counters[] = { 0, 0, 0, 0, 0 };
Class Room Practice

WAP that will take n integer numbers into an array, and then reverse all
the integers within that array. Finally print them all from 0 index to last
valid index.

Sample input Sample output


5 5 4 3 2 1
1 2 3 4 5
6 1 0 9 3 8 2
2 8 3 9 0 1

6-Jul-22 15
Character arrays
#include <stdio.h>
int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
int i;
for ( i = 0; i < 6; ++i )
printf ("%c", word[i]);
printf ("\n");
return 0;
}

a special case of character arrays: the character string type =>in a later chapter
Multidimensional arrays
• C language allows arrays of any number of dimensions
• Two-dimensional array: matrix

int M[4][5]; // matrix, 4 rows, 5 columns


// M[i][j] – element at row i, column j

int M[4][5] = {
{ 10, 5, -3, 17, 82 },
{ 9, 0, 0, 8, -7 },
{ 32, 20, 1, 0, 14 },
{ 0, 0, 8, 7, 6 }
};
int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7,
32,20, 1, 0, 14, 0, 0, 8, 7, 6 };
Example: Typical matrix processing
#define N 3
#define M 4
int main(void) {
int a[N][M];
int i,j;
/* read matrix elements */
for(i = 0; i < N; i++)
for(j = 0; j< M; j++) {
printf("a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]);
}
/* print matrix elements */
for(i = 0; i < N; i++) {
for(j = 0; j< M; j++)
printf("%5d", a[i][j]);
printf("\n");
}
return 0;
}

You might also like