1 / 43

# One-Dimensional Arrays - PowerPoint PPT Presentation

One-Dimensional Arrays. Introduction. A one-dimensional array is a sequence of homogenous elements stored in contigous memory locations Motivating example: Suppose we need to store 100 scores in main memory. //using simple variables int x0, x1, x2, …, x99; x0x1…x99

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

One-Dimensional Arrays

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

## One-Dimensional Arrays

### Introduction

• A one-dimensional array is a sequence of homogenous elements stored in contigous memory locations

• Motivating example: Suppose we need to store 100 scores in main memory.

//using simple variables

int x0, x1, x2, …, x99; x0x1…x99

cin>>x0;

cin>>x1;

cin>>x2;

cin>>x99;

x[0] x[1] … x[99]

//using arrays

int x[100];

for(int i=0; i<=99; i++) cin>>x[i];

### Declaring One-Dimensional Arrays

• The general form of an array declaration

data_typearray_name[expression];

• The data_type is the type of array elements. The array_name is a user defined identifier (similar to variable name). The expression must evaluate to a positive integer and it cannot contain variables.

• Examples

int x[100] ; //x is an array of 100 integers (200 bytes)

double z,w[50],u[30];

char name[20], ch;

int n, m=5;

#define k 5

cin>>n;

int d[n]; // compiler error

int d[m]; // compiler error

int d[k]; // ok

### Array Initiliazation

• An array can be declared and initialized to some values

• Examples

int a[5]={2,3,1,1,0}; //valid a[0]=2, a[1]=3, a[2]=1, a[3]=1

int b[5]={2}; //valid b[0] = 2, b[1] = 0, b[2] = 0

int d[5]={1,2,3,4,5,6}; //compiler error

int c[ ]={1,3}; //valid

int e[ ]; // compiler error (unknown size)

char f[3]={‘a’,’b’,’c’}; //valid

double h[2]={1.1,-1.7};

### Using Array Elements

Array elements can be used wherever simple variables can be used. Examples:

int A[5]={2,5,12,4,0};

A[2]++; //A[2] = A[2] + 1;

cout<<A[2]; //13

a[0]=a[1]+a[2]*3%a[3]; //if A array is used, 5 is displayed

int I=4;

A[I-1]=A[I];

cout<<A[3];

A[A[4]]++;

cout<<A[A[4]]++; //3 displayed

//cout<<A[3]>A[2];

A[3]=A[2]=A[1]; //5

I=2;

if (A[I]>A[I-1]) //4 displayed

cout<<A[I+1];

else

cout<<A[I-2];

for(A[I]=0; A[I]>A[I+2]; I++) cout<<A[I]; //nothing displayed

### Example: Givenfloat B[100]={ …};Write a code segment to print the values of B each element on a separate line.

int I;

for( I=0; I <=99; I++ )

cout<<B[I]<<endl;

### Example: Givenfloat B[100]={ …};Write a code segment to print the values of B each two elements on a separate line.

int I;

for( I=0; I <=98; I+=2 )

cout<<B[I]<<“ ”<<B[I+1]<<endl;

### Example: Givenfloat B[100]={ …};Write a code segment to print the values of B in reverse order.

int I;

for( I=99; I >=0; I-- )

cout<<B[I]<<endl;

### Example: Givenfloat B[100]={ …};Write a code segment to count the number of negative values in B.

int I,count=0;

for( I=0; I <=99; I++ )

if (B[I]<0) count++;

cout<<count;

Example: Given double B[100]={ …};double C[100]={ …};double D[100];Write a code segment to add B and C and store the result in D.

int I;

for( I=0; I <=99; I++ )

D[I]=B[I]+C[I];

### Example: Given double B[100]={ …};double C[100]={ …};Write a code segment to compute the dot product B.C

int I,result=0;

for( I=0; I <=99; I++ )

result+=B[I]*C[I];

### Example: Givenlong X[100]={ …};Write a code segment to print the maximum value in X.

int I, max;

for( max=X[0], I=1; I <=99; I++ )

if (X[I]>max) max=X[I];

cout<<max;

### Example: Givenlong X[100]={ …};Write a code segment to print the location of the maximum value in X.

int I, max, L;

for( max=X[0],L=0, I=1; I <=99; I++ )

if (X[I]>max){

max=X[I];

L=I;

}

printf(“the location is %d”,L);

### Example: Givenlong X[100]={ …};Write a code segment to count the number of values below average in X.

int I, sum, avg, count;

for( I=0, sum=0; I <=99; I++ )

sum+=X[I];

avg=sum/100;

for( I=0, count=0; I <=99; I++ )

if (X[I]<avg) count++;

printf(“the number of values =%d”,count);

### Example: Given long X[100]={ …};Write a code segment to test if elements in X are sorted.

int I;

for( I=0; I <=98 && X[I]<=X[I+1]; I++ );

if (I==99)

cout<<“sorted”;

else

cout<<“not sorted”;

### Example: Given long X[100]={ …};long Y[100]={ …};Write a code segment to test if X=Y.

int I;

for( I=0; I <=99 && X[I]==Y[I]; I++ );

if (I==100)

cout<<“equal”;

else

cout<<“not equal”;

### Example:Given long X[100]={ …};Write a code segment to reverse the values in X.

int I, Y[100];

for( I=0; I <=99; I++ ) Y[I]=X[99-I];

for( I=0; I <=99; I++ ) X[I]=Y[I];

### Example: Givenint X[100]={ …};Assume all values in X are between 0 and 19.Write a code segment to histogram the values in X

#include <iostream.h>

void main(){

int i,j;

int a[100]={1,2,3,4,5,5,5,6,7,6,7,8,9,6,7,8,9,6,

7,8,9,0,0,0,1,1,1,3,3,5,2,1,1,1,1,4,

4,4,4,1,1,1,3,4,0,5,1,8,9,9,

11,12,3,14,15,15,15,16,17,16,17,18,19,6,7,8,9,6,

17,8,9,10,10,1,1,11,1,13,13,15,12,1,1,1,1,14,

14,4,4,1,11,1,13,14,10,5,1,18,9,19};

int count[20]={0};

for(i=0; i<=99; i++) count[a[i]]++; //the value in the big array is the subscript in the //small array

for(i=0; i<=19; i++){//to display the elements in the count array

cout<<i<<” ”;

for(j=1; j<=count[i]; j++) cout<<”*”;//to display stars count[i] times

cout<<endl;

}

}

Example: Givenint X[100]={ …};Write a code segment to compute the standard deviation of values in Xstandard deviation = √∑(xi – µ)2/n-1

int I, sum;

double avg;

for(I=0, sum=0; I<=99;I++) sum+=X[I];

avg=(double) sum/100;

for(I=0, sum=0; I<=99; I++) sum+=pow(X[I]-avg, 2);

cout<<sqrt(sum/99);

### Example: Write a program to convert from decimal into binary

#include <iostream.h>

void main( ){

int num, I, count, A[1000];

cin>>num;

for (count=0; num ; num/=2) {

A[count]=num%2;

count++;

};

for(I=count-1; I>=0; I--) cout<<A[I];

}

### Arrays of Characters

• One-dimensional arrays of characters are used to store names (strings).

• Names stored in an array must terminate with NULL character. Also represented as ‘\0’

• The array

char N[4];

can store a name consisting of at most 3 characters.

• Arrays of characters can be declared and assigned strings in many ways:

char N[4]=”Ali”; // stores the 4 characters ‘A’ ‘l’ ‘i’ NULL in array N

char N[ ]=”Ali”; // defines an array of 4 elements and stores the 4 // characters ‘A’ ‘l’ ‘i’ and NULL in array N

char N[4]={ ‘A’ , ‘l’ , ‘i’ , NULL}; // stores the 4 characters ‘A’ ‘l’ // ‘i’ NULL in array N

• Extra Elements Are Filled Automatically With NULL

char N[4]={ ‘A’ , ‘l’ }; //Fills the last two elements with NULL

char N[5]={ ‘A’ , ‘h’,’m’,’a’,’d’ }; // Logical error: the string does not // end with NULL

### String Assigment and I/O

char N[10];

N=”ali”; //syntax error

N={‘A’ , ‘l’ , ‘i’ , NULL}; //syntax error

cin>>N; //ok

N[0]= ‘A’; N[1]= ‘l’; N[2]= ‘i’; N[3]= NULL; //ok

cout<<N; // prints Ali

cin>>N[0]; cin>>N[1]; cin>>N[2]; N[3]= NULL; //ok

N[2]=NULL;

cout<<N; // prints ah. cout keeps printing until NULL is reached.

### Some Differences Between Character Arrays and Other Arrays

char N[10]={…};

int A[5]={…};

cin >>N// ok

cin>>A// compiler error

cout<<N; //ok, prints the string in N

cout<<A; //Does not print the values in A

### Write a program to read a string and print the number of characters in the string.

#include <iostream.h>

void main(){

int i;

char N[20];

cin>>N;

for(i=0; N[i]; i++);

cout<<i;

}

### Write a program to read a string and print the last character in the string.

#include <iostream.h>

void main(){

int i;

char N[20];

cin>>N;

for(i=0; N[i]; i++);

cout<<N[i-1];

}

### Write a program to read a string and delete the last (not NULL) character in the string.

#include <iostream.h>

void main(){

int i;

char N[20];

cin>>N;

for(i=0; N[i]; i++);

N[i-1]=NULL;

}

### Write a program to read a string and print the characters of the string each on a separate line.

#include <iostream.h>

void main(){

int i;

char N[20];

cin>>N;

for(i=0; N[i]; i++)

cout<<N[i]<<endl;

}

### Write a program to read a string and print it in reverse order.

#include <iostream.h>

void main(){

int i;

char N[20];

cin>>N;

for(i=0; N[i]; i++);

for(int j=i-1; j>=0; j--)

cout<<N[j];

}

### Example: Givenchar X[100]={ …};Write a code segment to capitalize every character in the string X

for(int i=0; X[i]; i++)

if(X[i]>=‘a’ &&X[i]<=‘z’)

X[i]=X[i]-’a’+’A’;

### Example: Givenchar X[100]= … ;char Y[100]= … ;Write a code segment to append the string Y at end of X.

int i;

for(i=0; X[i]; i++);

for(int j=0; Y[j]; i++, j++) X[i]=Y[j];

X[i]=NULL;

Example: Write a program to read a string consisting of small letters and print the number of occurrences of each letter a..z in this string.

#include <iostream.h>

void main(){

int i,count[26]={0};

char name[20];

cout<<”Enter Name:”;

cin>>name;

for(i=0; name[i]!=NULL; i++)

count[name[i]-‘a’]++;

for(i=0; i<=25; i++)

cout<<endl<<”count(”<<(char) (‘a’+i)<<”)=”<<count[i];

}

Example: Write a program to read a string consisting of small letters and print the number of occurrences of each letter a..z in this string.

#include <iostream.h>

void main(){

int i,count[26]={0};

char name[20];

cout<<”Enter Name:”;

cin>>name;

for(i=0; name[i]!=NULL; i++)

count[name[i]-‘a’]++;

for(i=0; i<=25; i++)

cout<<endl<<”count(”<<(char) (‘a’+i)<<”)=”<<count[i];

}

### Example: Write a program to read 10 names and find the number of names starting with a.

#include <iostream.h>

void main(){

char name[20];

int i, count=0;

for(i=1; i<=10; i++){

cin>>name;

if (name[0]=='a') count++;

}

cout<<endl<<"Number of names starting with a ="<<count;

}

### Example: Write a program that reads 20 strings and finds the length of the shortest string .

#include <iostream.h>

void main(){

char name[20];

int shortestLength=1000, j ,i;

for(i=1; i<=20; i++){

cin>>name;

for(j=0; name[j]; j++);

if(j<shortestLength) shortestLength=j;

}

cout<<endl<<“shortest string length is "<<shortestLength;

}

### Example:Write a program to determine the location of a character in a string (if it occurs) .

#include <iostream.h>

void main(){

char name[20], ch;

int i;

cin>>name;

cin>>ch;

for(i=0; name[i]!=ch && name[i]!=NULL ; i++);

if (name[i]==ch)

cout<<“Location=”<<i;

else

cout<<ch<<“does not exist in ”<<name;

}

### Example:Write a program to determine the location of a substring in a string (if it occurs) .

#include <iostream.h>

void main(){

char S1[20], S2[20];

int I, J, flag=1;

cout<<“input string”;

cin>>S1;

cout<<“input sustring”;

cin>>S2;

for(i=0; s1[i] && flag; i++){

int k=i;

for(j=0; S2[j]&&S2[j]==S1[k]; j++,k++);

if (S2[j]==NULL) flag=0;

}

if (flag==0)

cout<<“Location=”<<i;

else

cout<<S2 <<“ does not exist in ”<<S1;

}

### Parallel Arrays

• Information about an object can be distributed over a number of one-dimentional arrays.

• Example: Information about students can be distributed over several arrays.

int student_id[50]={10432187, … };

int exam1[50]={70, … };

int exam2[50]={72, … };

int final_exam[50]= {68, … };

Example: Givenint student_id[50]={10432187, … };int exam1[50]={70, … };int exam2[50]={72, … };int final_exam[50]= {68, … };Write a code segment to compute the final grades of the students. Assume exam1 and exam2 has 25% each and the final exam has 50%.

double G;

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

G=0.25*exam1[i]+0.25*exam2[i]+

0.5*final_exam[i];

cout<<endl<<student_id[i]<<“ ”<<G;

}

Example: Givenint student_id[50]={10432187, … };int exam1[50]={70, … };int exam2[50]={72, … };int final_exam[50]= {68, … };Write a code segment to print the scores of a student given the ID .

int N;

cin>>N;

for(int i=0; i<=49 &&student_id[i]!=N; i++);

if (i==50)

cout<<“student id does not exist”;

else

cout<<exam1[i]<<exam2[i]<<final_exam[i];

Example: Givenint student_id[50]={10432187, … };int exam1[50]={70, … };int exam2[50]={72, … };int final_exam[50]= {68, … };Write a code segment to count the number of students passing in the first exam and failing in the second exam .

int count=0;

for(int i=0; i<=49; i++)

if (exam1[i]>=60 && exam2[i]<60)

count++;

cout<<count;

Example: Givenint student_id[50]={10432187, … };int exam1[50]={70, … };int exam2[50]={72, … };int final_exam[50]= {68, … };Write a code segment to print the ID of the student having the maximum score in the first exam.

int max, L;

for(int i=0, max=exam2[0], L=0; i<=49; i++)

if (exam2[i]>max){

max=exam2[i];

L=I;

};

cout<<student_id[L];

Example: Givenint student_id[50]={10432187, … };int exam1[50]={70, … };int exam2[50]={72, … };int final_exam[50]= {68, … };Write a code segment to find which of the 3 exams has the highest number of passing students.

int count1=0, count2=0, count3=0, i;

for(i=0; i<=49; i++) if (exam1[i]>=60)count1++;

for(i=0; i<=49; i++) if (exam2[i]>=60)count2++;

for(i=0; i<=49; i++) if (final_exam1[i]>=60)count3++;

if (count1>=count2)

if(count1>=count3)

cout<<“exam1”;

else

cout<<“exam3”;

else

if (count2>=count3)

cout<<“exam2”;

else

cout<<“exam3”;