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

arrays & string

The document provides an overview of arrays and strings in programming, covering their definitions, declarations, and various operations such as sorting and searching. It discusses single-dimensional and multi-dimensional arrays, including examples and syntax for initialization and manipulation. Additionally, it introduces strings as arrays of characters and demonstrates input/output operations with strings.

Uploaded by

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

arrays & string

The document provides an overview of arrays and strings in programming, covering their definitions, declarations, and various operations such as sorting and searching. It discusses single-dimensional and multi-dimensional arrays, including examples and syntax for initialization and manipulation. Additionally, it introduces strings as arrays of characters and demonstrates input/output operations with strings.

Uploaded by

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

1

Arrays and strings


Outline
4.1 Introduction
4.2 Arrays
4.3 Declaring Arrays
4.4 Examples Using Arrays
4.5 Passing Arrays to Functions
4.6 Sorting Arrays
4.7 Case Study: Computing Mean, Median and Mode Using Arrays
4.8 Searching Arrays: Linear Search and Binary Search
4.9 Multiple-Subscripted Arrays

2003 Prentice Hall, Inc. All rights reserved.


2

you will be able to


• discuss how to group related data items together with the use of arrays.
• explain single dimension, two dimensional and multi-dimensional arrays
• state what are strings
• use various standard string library functions and in programs
• create a two dimensional array of strings
• develop a number of programs using arrays.

2003 Prentice Hall, Inc. All rights reserved.


Arrays

• So far we have worked primarily with primitive


variables
– One characteristic of primitive variables is that they hold one
value at a time.
• int x = 100 – can only hold one integer value at a time
(100 at this time)
• Imagine that you want to hold the names of 100
people at a time.
– What would you have to do?
• Declare 100 variables, one for each name.
– Better solution: Use Arrays.

2003 Prentice Hall, Inc. All rights reserved.


4

4.1 Introduction

• Arrays
• An array is a collection of data elements that are of the
same type and share a common name
• (e.g., a collection of integers, collection of characters,
collection of doubles).
• Array Applications:
• Given a list of test scores, determine the maximum and
minimum scores.
• Read in a list of student names and rearrange them in
alphabetical order (sorting).

2003 Prentice Hall, Inc. All rights reserved.


Array Declaration

• Syntax:
<type> <arrayName>[<array_size>]
• The array elements are all values of the type <type>.
• The size of the array is indicated by <array_size>, the
number of elements in the array.
• <array_size> must be an int constant or a constant
expression. Note that an array can have multiple dimensions.

2003 Prentice Hall, Inc. All rights reserved.


Array Declaration
// array of 10 uninitialized ints

int Ar[10]; // array of 10 ints


Array name is Ar
Size is 10

2003 Prentice Hall, Inc. All rights reserved.


Subscripting

• To access an individual element we must apply a subscript


to array named Ar.
– A subscript is a bracketed expression.
• The expression in the brackets is known as the index.
– First element of array has index 0.
Ar[0]
– Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
– Last element has an index one less than the size of the array.
Ar[9]
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --

2003 Prentice Hall, Inc. All rights reserved.


Subscripting

// array of 10 uninitialized ints


int Ar[10];
--
Ar[3] = 1;
int x = Ar[3]; 1 --

-- -- --

0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]

2003 Prentice Hall, Inc. All rights reserved.


9

4.2 Arrays
Name of array (Note
that all elements of
this array have the
same name, c)

c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78

Position number of the


element within array c

2003 Prentice Hall, Inc. All rights reserved.


10

• Initializing arrays
– For loop
• Set each element
for (i=0; i<10; i++)
{ scanf(“%d”, &marks[i]);}
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
2003 Prentice Hall, Inc. All rights reserved.
11

• Array size
– Can be specified with constant variable (const)
• const int size = 5;
#define size 5
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables

– Array DECLARATION:
– int marks[size];
Or
int marks [size ]= {1, 3, 2, 48, 34)

2003 Prentice Hall, Inc. All rights reserved.


12

• An array is a collection of similar elements


• - The individual values in the array are called as
elements
• - The first element in the array is numbered 0
• - Each individual element in an array is accessed
by its position in the array.
• This position is called the array subscript or index
number.
• - The array has to be declared for type and
dimension before it can be used
• - All the elements in an array are stored in
contiguous memory locations
2003 Prentice Hall, Inc. All rights reserved.
13

Program to find average of 5 numbers

main()
{
int num[5];
int sum, i;
float avg;
sum = 0;
for(i =0; i< 5;i++)
{
scanf(“%d”, &num[i]);
sum = sum + num[i];
}
avg = sum/5;
printf(“The average of numbers is %7.2’’, avg);
}
2003 Prentice Hall, Inc. All rights reserved.
14
To find the smallest number in an array
#define MAX 20
main()
{
int i, n, min, num[MAX];
printf(“\nHow many elements do you wish to enter ? :”);
scanf(“%d”, &n);
printf(“Enter elements of array :\n”);
for(i=0; i < n; i++)
scanf(“%d”, &num[i]);
min = num[0];
for (i = 1; i < n; i++)
{
if(num[i] <min)
min = num[i];
}
printf(“\nThe smallest element of the array is : %d”, min); }
2003 Prentice Hall, Inc. All rights reserved.
15
Program to input numbers into array a and then
copy them to array b
main()
{
int i, a[10], b[10];
for (i = 0; i< 10; i++)
{
printf(“Enter element:);
scanf(“%d”, & a[i]);
printf(“\n”);
}
for (i = 0; i< 10; i++)
b[i] = a[i];
for (i = 0; i< 10; i++)
printf(“%d\t%d\n”, a[i], b[i]);
}

2003 Prentice Hall, Inc. All rights reserved.


16

• To sort n numbers

2003 Prentice Hall, Inc. All rights reserved.


17

main()
{
int i, j, temp;
float num[50]; printf(“\nThe sorted array :\n”);
printf(“\nEnter elements of array :”); for(i=0;i<5;i++)
for (i=0; i<5; i++) printf(“%6.2f\n”, num[i]);
scanf(“%f”, &num[i]); }
for(i = 0; i< 4; i++)
{
for(j = i+1; j<5; j++)
{
if(num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;}
}
}
}
2003 Prentice Hall, Inc. All rights reserved.
18

Homework

1 a. Enter elements into an array of type float.


Determine how many of them are positive and how
many are negative. Assume an array size of 15.
b. Modify the above program and write functions to
i. store all the positive numbers in a separate array
and all negative numbers in a different array.
ii. Print the sum of elements of these new arrays

2003 Prentice Hall, Inc. All rights reserved.


19

Two dimensional Arrays

• possible to declare arrays with two or more


dimensions.
• A two dimensional array is also called a matrix.
• Such a matrix or a table can be stored in a two
dimensional array
• Subject marks of 5 students in 3 subjects

2003 Prentice Hall, Inc. All rights reserved.


20

Declaration of 2-d arrays

• The two dimensional array can be declared as


follows :
• type array_name[row_size][col_size];
eg:- studnt_marks[5][3]

2003 Prentice Hall, Inc. All rights reserved.


21

Initialising Two Dimensional Arrays :

• can also be initialised like the one dimensional


arrays with their declaration followed by the list of
values of the elements
• For example :
int arr[2][3] = {10,5,3,15,20,25};
or
int arr[2][3] = {{10, 5, 3}, {15, 20, 25}};
or
int arr[2][3] =
{
{10,5,3},
{15,20,25}
};
2003 Prentice Hall, Inc. All rights reserved.
22

• when initialising a two dimensional array the first


dimension i.e. the row is optional, however the
second dimension the column is a must.

int arr[][3] = {10,5,3,15,20,25};

Write a program to calculate sum of elements in


rows of the array

2003 Prentice Hall, Inc. All rights reserved.


23
main() p for(i=0; i< rows; i++)
#define ROWS 50 {
#define COLS 50 sum = 0;
main()
for(j = 0; j < cols; j++)
{
{
int arr1[ROWS][COLS], i, j, rows,
cols, sum; sum = sum + arr1[i][j];
printf(“\n Enter number of rows :”); }
scanf(“%d”,&rows); printf(“%d\t”, sum);
printf(“\nEnter number of columns :”); printf(“\n”);
scanf(“%d”, &cols); }
for(i=0; i< rows; i++)
}
{
for(j = 0; j < cols; j++)
{
printf(“\nEnter value :”);
scanf(“%d”, &arr1[i][j]);
}
}
2003 Prentice Hall, Inc. All rights reserved.
24

Multidimensional arrays.

• C allows arrays of more than 2 dimensions. Such


arrays are multidimensional arrays.
• The exact limit of the number of dimensions is
dependant on the compiler.
• Multidimensional arrays are rarely required.
• int arr1 [2][3][4];
• A three dimensional array can be considered to be
a two dimensional array in another array.
• The outermost array is an array which has two
elements where each element itself is a two
dimensional array whose dimensions are [3][4].
2003 Prentice Hall, Inc. All rights reserved.
25

int arr1 [2][3][4] = {


{
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}
},
{
{5, 5, 5, 5},
{6, 6, 6, 6},
{7, 7, 7, 7},
}
};

2003 Prentice Hall, Inc. All rights reserved.


26

Strings
• Strings
- Arrays of characters enclosed within double
quotes
– All strings end with null ('\0')
– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0’ };
– Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'

2003 Prentice Hall, Inc. All rights reserved.


27

Which is correct?Why?

1. char color[3] = "RED”;


2. char color[] = "RED";

• 1 can be corrected as
• char color[4] = "RED";

2003 Prentice Hall, Inc. All rights reserved.


28

Reading and Writing Strings :

main()
{
char name[15];
printf(“Enter your name :”);
scanf(“%s”, name);
printf(“Good Morning %s”, name);
}

char name[ 80 ] ;
scanf (“ %[ ^\n ] “ , name ) ;

2003 Prentice Hall, Inc. All rights reserved.


29

Reading and Writing Strings : gets and puts

• The general form of a string variable is”


char string_name[size];
Eg:- char name[ 15 ];
main()
{
char name[25];
printf(“Enter your name :”);
gets(name);
puts(“Good Morning”);
puts(name);
}

2003 Prentice Hall, Inc. All rights reserved.


getchar() and putchar()
30

Program to read a line with the help


of getchar()*/
main() line_1 [i] = ‘\0’;
{ i = 0;
char ch1, line_1[81]; while((ch1 = line_1[i]) !=’\0')
int i; {
printf(“Enter a line of text. Press putchar(ch1);
Enter to end\n”); i++;
i = 0; }
while ((ch1 = getchar()) != ‘\n’) }
{
line_1[i] = ch1;
i = i + 1;
}

2003 Prentice Hall, Inc. All rights reserved.


31

Additional programs for string manipulation

//copy one string to another


{
char str1[20], str2[20];
int i;
printf(“Enter string :”);
scanf(“%s”, str1);
for(i = 0;str1[i] !=’\0'; i++)
str2[i] = str1[i];
str2[i] = ‘\0’;
printf(“\nThe copied string is %s”, str2);
printf(“\nThe length of the string is : %d”, i);
}

2003 Prentice Hall, Inc. All rights reserved.


32
/* String concatenation Program */
main()
{
char str1[50], str2[25];
int i, j ;
printf(“\nEnter first string :”);
scanf(“%s”,str1);
printf(“\nEnter second string :”);
scanf(“%s”, str2);
i = 0;
while(str1 [i] !=’\0')
i = i + 1;
for(j = 0; str2[j] != ‘\0’;j++)
{
str1[i] = str2[j];
i = i + 1;
}
str1[i) = ‘\0’;
printf(‘\nConcatenated string is %s”, str1);
}

2003 Prentice Hall, Inc. All rights reserved.


33

String Handling functions

• C supports a large number of string handling


functions in the standard library "string.h".

2003 Prentice Hall, Inc. All rights reserved.


34

• 1.strcat()- concatenates two given strings


• strcat ( str2, str1 ); – str1 is concatenated at the
end of str2.
char str1[] = "This is ",
str2[] = “a pen";
strcat(str1,str2);
2. char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0’};
Strlen(a) ; //7
Strlen(b) ; //7

2003 Prentice Hall, Inc. All rights reserved.


35

4.strcpy()
char str1[10]= "awesome";
char str2[10]; char str3[10];
strcpy(str2, str1);
5.strcmp()

2003 Prentice Hall, Inc. All rights reserved.


36

2003 Prentice Hall, Inc. All rights reserved.


37

Passing Arrays to Functions

• An entire array can be passed to a function as an


argument.
• Arrays passed-by-reference
– Functions can modify original array data
– Value of name of array is address of first element
• Function knows where the array is stored
• Can change original memory locations
• Individual array elements passed-by-value
– Like regular variables
– square( myArray[3] );

2003 Prentice Hall, Inc. All rights reserved.


38

Passing Arrays to Functions

• Specify name without brackets


– To pass array myArray to myFunction
int myArray[ 24 ];

myFunction( myArray, 24 );
– Array size usually passed, but not required

2003 Prentice Hall, Inc. All rights reserved.


39

Passing Arrays to Functions

• Functions taking arrays


– Function prototype
• void modifyArray( int b[], int arraySize );
• void modifyArray( int [], int );
– Names optional in prototype
• Both take an integer array and a single integer
– No need for array size between brackets
• Ignored by compiler
– If declare array parameter as const
• Cannot be modified (compiler error)
• void doNotModify( const int [] );

2003 Prentice Hall, Inc. All rights reserved.


40
#include <stdio.h>
void modify(int a[]); /* function prototype void modify ( int a [ ] )
*/ {
main ( ) int count;
{
printf("\nFrom the function,
int count, a[3]; /* array definition */
after modifying the
printf('\nFrom main, before calling the
function:\n'); values:\nn);
for (count = 0; count <= 2; ++count) for (count = 0; count <= 2;
{ ++count) {
a[count] = count + 1; a[count] = -9;
printf('a[%d] = %d\nn, count, a[count]); p r i n t f ( " a [ % d ] = %d\n",
} count, a[count]);
modify(a);
return;
printf('\nFrom main, after calling the
function:\n"); }
for (count = 0; count <=2; ++count)
printf("a[%d] = %d\n", count, a[count]);
}
2003 Prentice Hall, Inc. All rights reserved.
41

2003 Prentice Hall, Inc. All rights reserved.


42

Sorting Arrays

• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element

2003 Prentice Hall, Inc. All rights reserved.


43

2003 Prentice Hall, Inc. All rights reserved.


44

void bubbleSort(int arr[], int n)


{
int i, j ,temp;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{ temp= arr[j];
arr[j]=arr[j+1];
arr[j+1]= temp;
}Prentice Hall, Inc. All rights reserved.
2003
45

#define MAX 20
main()
{
int i, n, min, num[MAX];
printf(“\nHow many elements do you wish to enter ?:”);
scanf(“%d”, &n);
printf(“Enter elements of array :\n”);
for(i=0; i < n; i++)
scanf(“%d”, &num[i]);

2003 Prentice Hall, Inc. All rights reserved.


46

bubbleSort(num, n);
printf(“Sorted array :\n”);
for(i=0; i < n; i++)
printf(“\n %d”, num[i]); }

2003 Prentice Hall, Inc. All rights reserved.


47
Case Study: Computing Mean, Median
and Mode Using Arrays

• Mean
– Average (sum/number of elements)
• Median
– Number in middle of sorted list
– 1, 2, 3, 4, 5 (3 is median)
– If even number of elements, take average of middle two
• Mode
– Number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)

2003 Prentice Hall, Inc. All rights reserved.


48
Searching Arrays: Linear Search and
Binary Search

• Search array for a key value


• Linear search
• Linear search
– Problem: Given an array arr[] of n elements, write a
function to search a given element x in arr[].
A simple approach is to do linear search, i.e
a.Start from the leftmost element of arr[] and one by
one compare x with each element of arr[]
b.If x matches with an element, return the index.
c.If x doesn’t match with any of elements, return -1.

2003 Prentice Hall, Inc. All rights reserved.


49

int search(int arr[], int n, int x) printf(“Enter elements of array


:\n”);
{
for(i=0; i < n; i++)
int i;
scanf(“%d”, &num[i]);
for (i=0; i<n; i++)
printf(“enter the element to
if (arr[i] == x) searched”);
return i; scanf(“%d”,&x);
return -1; pos=search(num, n, x);
} if(pos==-1)
main() printf(“elements is not in list”);
{ else
int i, n, pos, num[MAX]; printf(“elements is at position:
printf(“\nHow many elements do you %d”,pos);
wish to enter ?:”); }
scanf(“%d”, &n);
2003 Prentice Hall, Inc. All rights reserved.
50
Searching Arrays: Linear Search and Binary
Search
• Binary search
– Only used with sorted arrays
– Compare middle element with key
• If equal, match found
• If key < middle
– Repeat search on first half of array
• If key > middle
– Repeat search on last half
– Very fast
• At most N steps, where 2N > # of elements
• 30 element array takes at most 5 steps
5
2 > 30

2003 Prentice Hall, Inc. All rights reserved.


51

2003 Prentice Hall, Inc. All rights reserved.


mid=(top+bot-1)/2; 52
main( )
if(a[mid]<x)
{
top=mid+1;
int a[100],i,n,x, mid, top, bot, c;
else
printf(“enter the array size;”);
if(a[mid]>x)
scanf(“%d”,&n);
bot=mid-1;
printf(“enter the array elements”);
for(i=1;i<=n;i++) else
scanf(“%d”,&a[i]); c=1;
top=1; bot=n; c=0; }
printf(“enter the element to searched”); if(c==1)
scanf(“%d”,&x); printf(“elements is at
position;%d”,mid);
while((top <=bot)&&(c==0))
else
{
printf(“elements is not in list”);
}
2003 Prentice Hall, Inc. All rights reserved.
53

• Implement a recursive function for binary search

2003 Prentice Hall, Inc. All rights reserved.


54

Selection sort

• The selection sort algorithm sorts an array by


repeatedly finding the minimum element
(considering ascending order) from unsorted part
and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
• 1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
• In every iteration of selection sort, the minimum
element (considering ascending order) from the
unsorted subarray is picked and moved to the
sorted subarray
2003 Prentice Hall, Inc. All rights reserved.
55

Selection sort- example

2003 Prentice Hall, Inc. All rights reserved.


56

void selectionSort(int arr[], int n)


{ int i, j, min_idx;
for (i = 0; i < n-1; i++)
{ // Find the minimum element in unsorted array
min = i;
for (j = i+1; j < n; j++)
{ if (arr[j] < arr[min])
{ min = j;
// Swap the found minimum element with the first element
temp= arr[min];
arr[min]=arr[i];
arr[i]= temp;
}} }}
2003 Prentice Hall, Inc. All rights reserved.

You might also like