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

Ch07 Arrays and Strings

This document provides an introduction and overview of arrays and strings in C++ programming. It begins with definitions of arrays, explaining that arrays allow grouping of similar data types and accessing elements via indices. It then gives several code examples demonstrating how to define, initialize, read from, write to, pass and manipulate one-dimensional and multi-dimensional arrays. The document also covers strings as arrays of characters, and examples for reading/writing strings with embedded blanks or multiple lines. Overall, the document serves as a tutorial on the basic concepts and usage of arrays and strings in C++.

Uploaded by

nidamah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Ch07 Arrays and Strings

This document provides an introduction and overview of arrays and strings in C++ programming. It begins with definitions of arrays, explaining that arrays allow grouping of similar data types and accessing elements via indices. It then gives several code examples demonstrating how to define, initialize, read from, write to, pass and manipulate one-dimensional and multi-dimensional arrays. The document also covers strings as arrays of characters, and examples for reading/writing strings with embedded blanks or multiple lines. Overall, the document serves as a tutorial on the basic concepts and usage of arrays and strings in C++.

Uploaded by

nidamah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

Introduction to Programming

Engr. Rashid Farid Chishti


[email protected]
Chapter 07: Arrays and Strings

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk

Arrays

In everyday life we commonly group similar


objects into units. We buy eggs by the carton.
In computer languages we also need to group
together data items of the same type. The most
basic mechanism that accomplishes this in C++
is the array.
Arrays can hold a few data items or tens of
thousands. The data items grouped in an array
can be simple types such as int or float, or
they can be user-defined types such as
structures and objects.
An array groups items of the same type. The
items in a in an array are accessed by an
index number. Using an index number to specify
an item allows easy access to a large number
of items.

Defining, Reading and Writing Array


// gets four ages from user, displays them
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int age[4], j; //array 'age' of 4 ints
for(j=0; j<4; j++){ //get 4 ages
cout << "Enter an age: ";
cin >> age[j]; //access array element
}
for(j=0; j<4; j++){ //display 4 ages
cout << "age[" << j << "] = " << age[j] << endl;
cout <<"Address " << &age[j] << " = " << age[j] <<
endl;
}
system("PAUSE"); return 0;
}

Calculating Average
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
double avg, sum = 0 ;
int i ; int marks[10] ; /* array declaration */
for ( i = 0 ; i <= 9 ; i++ ){
cout << "\nEnter marks ";
cin >> marks[i]; /* store data in array */
}
for ( i = 0 ; i <= 9 ; i++ )
sum = sum + marks[i] ; /* read data from array*/
avg = sum / 10 ;
cout << "\n Average marks = " << avg <<endl;
system("PAUSE"); return 0;
}

Using Direct Access on an Array


// Using Direct Access on Array
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int mem[]={50,60,70} ; // Initialize the array
cout << "mem[0] = " << mem[0] << endl;
cout << "mem[1] = " << mem[1] << endl;
cout << "mem[2] = " << mem[2] << endl;
mem[0] = 80;
mem[1] = 90;
mem[2] = 100;
cout << endl;
cout << "mem[0] = " << mem[0] << endl;
cout << "mem[1] = " << mem[1] << endl;
cout << "mem[2] = " << mem[2] << endl;
system("PAUSE"); return 0;
}

Printing in Reverse Order


#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
const int SIZE=5; // defines the size N for 5 elements
double a[SIZE];
// declares the arrays elements as
type double
cout << "Enter " << SIZE << " numbers:\t";
for (int i=0; i<SIZE; i++)
cin >> a[i];
cout << "In reverse order: ";
for (int i=SIZE-1; i>=0; i--)
cout << " " << a[i];
system("PAUSE"); return 0;
}

Out of Bounds
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
float a[] = { 22.2,44.4, 66.6 };
float x=11.1;
cout << "I m going to Crash " << endl;
cin >> x;
a[3333] = 88.8; // ERROR: index is out of bounds!
system("PAUSE"); return 0;
}

Passing Array to Function


#include <iostream>
#include <stdlib.h>
using namespace std;
int sum(int[],int); // declaration
int main(){
int a[] = { 11,33, 55,77 };
int size = sizeof(a)/sizeof(int);
cout << "sum(a,size) = " << sum(a,size) << endl;
cout << endl << a[0] << endl;
system("PAUSE"); return 0;
}
int sum(int a[],int n){
int sum=0;
for (int i=0; i<n; i++)
sum += a[i];
a[0] = 100; return sum;
}

n Dimensional Arrays
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){ const int row=2, col=3; int i,j;
int ary[row][col] = {
{11,12,13},
{21,22,23}
};
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}
cout << endl;
}
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){
cout << &ary[i][j] << "="<<ary[i][j]<<"\t";}
cout << endl;}
system("PAUSE"); return 0;
}

n Dimensional Arrays

ary[0][0]= 0x22ff40 = 11

11 12 13
21 22 23

ary[0][1]= 0x22ff44 = 12
ary[0][2]= 0x22ff48 = 13
ary[1][0]= 0x22ff4C = 21
ary[1][1]= 0x22ff50 = 22
ary[1][2]= 0x22ff54 = 23

2-Dimensional Arrays
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){ const int row=3, col=3; int i,j;
int ary[row][col] = {
{11,12,13},
{21,22,23},
{31,32,33}
};
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}
cout << endl;
}
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){
cout << &ary[i][j] << "="<<ary[i][j]<<"\t";}
cout << endl;}
system("PAUSE"); return 0; }

3-Dimensional Arrays

ary[0][0]= 0x22ff30 = 11
ary[0][1]= 0x22ff34 = 12
ary[0][2]= 0x22ff38 = 13
ary[1][0]= 0x22ff3C = 21

11 12 13
21 22 23

31 32 33

ary[1][1]= 0x22ff40 = 22
ary[1][2]= 0x22ff44 = 23
ary[2][0]= 0x22ff48 = 31
ary[2][1]= 0x22ff4C = 32
ary[2][2]= 0x22ff50 = 33

Calculating Square of a Matrix


#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){ const int row=3, col=3; int i,j;
int A[row][col];
cout << "Square of a " <<row <<"x"<<col<<"Matrices"<<endl;
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){
cout << "A[" << i+1 << "][" << j+1 << "]= ";
cin >> A[i][j];
}
}
for(i=0 ; i< row ; i++)
for(j=0 ; j<col; j++)
A[i][j] = A[i][j]*A[i][j];
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++)
cout << A[i][j] << "\t";
cout << endl;
}
system("PAUSE"); return 0;
}

Passing 2D Array to Function


#include <iostream>
#include <stdlib.h>

using namespace std;


void get_data(float a[][3],int row, int col){
int i,j;
for (i=0; i<row; i++)
for (j=0; j<col; j++){
cout << "A["<<i+1<<"]["<<j+1<<"]:";
cin >> a[i][j];}
}
void show_data(float a[][3],int row, int col){
int i,j;
for (i=0; i<row; i++){
for (j=0; j<col; j++)
{cout << a[i][j] << "\t";}
cout << endl; }
}
int main(){
float matrix[4][3]; // 4 rows and 3 columns
get_data(matrix,4,3);
show_data(matrix,4,3);
system("PAUSE"); return 0;}

Passing 3D Array to Function (1/2)


#include <iostream>
#include <stdlib.h>
using namespace std;
void get_data(float a[][3][2],int row, int col,int page){
int i,j,k;
for (k=0; k<page; k++){
for (i=0; i<row; i++){
for (j=0; j<col; j++){
cout <<"A["<< i <<"]["<< j <<"]["<< k <<"]:";
cin >> a[i][j][k];
} // end of for (j=0
} // end of for (i=0
} // end of for (k=0
}

Passing 3D Array to Function (2/2)


void show_data(float a[][3][2],int row, int col, int page){
int i,j,k;
for (k=0; k<page; k++){
for (i=0; i<row; i++){
for (j=0; j<col; j++){
cout << a[i][j][k] << "\t";
}
cout << endl;
}
cout << endl;
}
}
int main(){
float matrix[4][3][2]; // 4 rows, 3 columns, 2 pages
get_data(matrix,4,3,2);
show_data(matrix,4,3,2);
system("PAUSE");
return 0;
}

Sorting Data Using Bubble Sort Algo


#include <iostream>
#include <stdlib.h>
using namespace std;
void print( float[], int );
void sort ( float[], int );
int main(){
int i; float data[10];
cout << "Enter 10 Numbers for Sorting \n";
for( i=0 ; i<10 ; i++ ){
cout << "Enter No." <<i+1<< ":" ;
cin >> data[i];
}
sort(data,10);
print(data,10);
system("PAUSE");
return 0;
}

Sorting Data Using Bubble Sort Algo


void sort( float a[], int n ){ // bubble sort:
for (int i=1; i<n; i++) // bubble up max{a[0..n-i]}:
for (int j=0; j<n-i; j++)
if (a[j] > a[j+1]){
float temp = a[j];
a[j]=a[j+1];
a[j+1] = temp;
}
}
void print( float a[], int n ){
cout << " Sorted Data is " << endl;
for (int i=0; i<n; i++)
cout << a[i] <<" ";
}

Using Character Array


#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main(){
char name[30]; // an array to store max 30 characters
cout << "What is your name? ";
gets(name);
// it also copies embedded blanks
cout << "Welcome Mr. " << name << endl;
// Value of Space=32 , Enter = 0
cout << "Tell me your friend's name: " ;
cin >> name;
// it copies up to first blank space
cout << "Your friend is Mr. " << name << endl;
cout << "\n [The Data in the array is] \n";
for (int i=0 ; i<30 ; i++)
cout << "Array[" << i << "]=" << name[i] << " ["
<< int(name[i]) << "]" << endl;
system("PAUSE"); return 0; }

Using C-string
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
char str[] = { 'M','.',' ','A','l','i',0,' ',
'I','I','U',0}; // char ch [] = "M. Ali";
int size = sizeof(str);
cout << "\n The Character Array Size is :" <<size
<< " Bytes" << endl;
for ( int i=0 ; i<size ; i++ )
cout << "str[" << i << "]=" <<str[i] <<" =["
<< int(str[i]) << "]" << endl;
cout << endl << str << endl;
system("PAUSE");
return 0;
}

Reading Embedded Blanks


// blanksin.cpp reads string with embedded blanks
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
const int MAX = 80;
// max characters in string
char str[MAX];
// string variable str
cout << "\nEnter a string: ";
// cin.get() means a member function get() of the stream
// class of which cin is an object
cin.get(str, MAX);
// put string in str
// first argument to get() is the array address where the
// string being input will be placed.
// The second argument specifies the maximum size of the
// array
cout << "You entered: " << str << endl;
system("PAUSE"); return 0; }

Reading Multiple Lines


// linesin.cpp
// reads multiple lines, terminates on '$' character
#include <iostream>
#include <stdlib.h>
using namespace std;
const int MAX = 2000; // max characters in string
char str[MAX]; //string variable str
int main(){
cout << "\nEnter a multiline string:\n";
cin.get(str, MAX, '$'); //terminate with $
cout << "You entered:\n" << str << endl;
for(int i=0 ; i<10 ; i++)
cout << str[i] << "=" << int(str[i]) << endl;
// Enter = 10, Space = 32;
system("PAUSE");
return 0;
}

Copying a String the Hard Way


// strcopy1.cpp
// copies a string using a for loop
#include <iostream>
#include <cstring> //for strlen()
#include <stdlib.h>
using namespace std;
int main(){ //initialized string
char str1[] =
"Oh, Captain, my Captain! "
"our fearful trip is done";
const int MAX = 80; int j; // MAX is size of str2 buffer
char str2[MAX]; //empty string
for( j=0; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = '\0'; //insert NULL at end
cout << str2 << endl; //display str2
system("PAUSE"); return 0;
}

Copying a String the Easy Way


// strcopy2.cpp
// copies a string using strcpy() function
#include <iostream>

#include <cstring> //for strcpy()


#include <stdlib.h>
using namespace std;
int main(){
char str1[] = "Tiger, tiger, burning bright\n"
"In the forests of the night";
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
strcpy(str2, str1); //copy str1 to str2
cout << str2 << endl; //display str2
system("PAUSE"); return 0; }

Array of Strings
// straray.cpp
// array of strings
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//An array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday" , "Saturday" };
for( int j=0 ; j<DAYS ; j++) //display every string
cout << star[j] << endl;
system("PAUSE");
return 0;
}

Array of Strings

Assignment #4
1.

Write and test the following function that returns through its reference
parameters both the maximum and the minimum values stored in an
array: void getExtremes(float& min, float& max, float a[], int n);

2.

Write and test the following function that returns dot product of two
vectors: float innerProduct(float a[], int n, float b[]);

3.

Write and test the following function:


double stdev(double x[], int n);
The function returns the standard deviation
of a data set of n numbers x0, , xn1

4.

Write a and test a program to calculate


Determinant and Multiplicative Inverse of a 3x3 matrix

Assignment #4
1.

2.

3.

Write a program that takes a string from the user. The program then
calculates the
Total number of Characters
Total number of words
Total number of lines

Write a program to calculate mean, median and mode of an


array
Write a program to convert a given year to its Roman
equivalent i.e.,
Decimal
Roman
1
i
5
v
10
x
50
l
e.g. 1988 = mdcccclxxxviii
1525 = mdxxv

Decimal
100
500
1000

Roman
c
d
m

You might also like