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

week10

This document covers arrays and strings in C programming, detailing single and multi-dimensional arrays, their initialization, and operations such as sorting and searching. It also discusses string manipulation, including string input/output functions and common string functions like strlen() and strcpy(). Additionally, it includes practical tasks and exercises for implementing array and string concepts.

Uploaded by

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

week10

This document covers arrays and strings in C programming, detailing single and multi-dimensional arrays, their initialization, and operations such as sorting and searching. It also discusses string manipulation, including string input/output functions and common string functions like strlen() and strcpy(). Additionally, it includes practical tasks and exercises for implementing array and string concepts.

Uploaded by

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

Week-10

Array and Strings


We’ll Learn Today

■ Single & Multi-Dimensional Arrays


■ Passing arrays to a function
■ Sorting
■ Searching
■ Strings
Arrays Name of array (Note that all
elements of this array have the
same name, c)

■ An array is a collection of variables of


a certain type, placed contiguously in
memory. c[0] -45
■ Array c[1] 6

❑ Group of consecutive memory locations c[2] 0


c[3] 72
❑ Same name and type c[4] 1543
■ To refer to an element, specify c[5] -89
❑ Array name c[6] 0
c[7] 62
❑ Position number
c[8] -3
■ Format: c[9] 1
arrayname[ position number ] c[10] 6453
❑ First element at position 0 c[11] 78

❑ n element array named c:


■ c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number of the
element within array c
Arrays (Cont’d)
■ Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
❑ Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
■ When defining arrays, specify
❑ Name
❑ Type of array
❑ Number of elements
arrayType arrayName[ numberOfElements ];
❑ Examples:
int c[ 10 ];
float myArray[ 3284 ];
■ Defining multiple arrays of same type
❑ Format similar to regular variables
❑ Example:
int b[ 100 ], x[ 27 ];
Arrays (Cont’d)
■ Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
❑ If not enough initializers, rightmost elements
become 0
int n[ 5 ] = { 0 }
■ All elements 0
❑ C arrays have no bounds checking
■ If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
❑ 5 initializers, therefore 5 element array
Items are stored at contiguous memory locations in arrays.

An array is a collection of data items of the same data type. And


it is also known as a subscript variable.

Advantages of Arrays?

It is used to represent multiple data items of the same type by


using only a single name.

Accessing any random item at any random position in a given


array is very fast in an array.
Syntax of Array Declaration

where N is the number of dimensions.


C Array Initialization
■ 1. Array Initialization with Declaration
C Array Initialization (Cont’d)
■ 2. Array Initialization with Declaration without Size

The size of the above arrays is 5 which is automatically deduced by the compiler.

If we initialize an array using an initializer list, we can skip


declaring the size of the array as the compiler can automatically
deduce the size of the array in these cases. The size of the array in
these cases is equal to the number of elements present in the
initializer list as the compiler can automatically deduce the size of
the array.
C Array Initialization (Cont’d)
■ 3. Array Initialization after Declaration (Using
Loops)
■ We initialize the array after the declaration by
assigning the initial value to each element
individually. We can use for loop, while loop,
or do-while loop to assign the value to each
element of the array.
Array Initialization after Declaration (Using Loops)
Arrays (Cont’d)
Using Arrays to Summarize Survey Results

■ Forty students were asked to rate the quality


of the food in the student cafeteria on a scale
of 1 to 10 (1 means awful and 10 means
excellent). Place the 40 responses in an
integer array and summarize the results of
the poll.
Example of 1D Array in C
Access Array Elements
■ We can access any element of an array in C using
the array subscript operator [ ] and the index
value i of the element.
■ One thing to note is that the indexing in the array
always starts with 0, i.e., the first element is at
index 0 and the last element is at N – 1 where N is
the number of elements in the array.
Example of Accessing Array Elements
using Array Subscript Operator
Update Array Element
Class Participation Task Week-10
Task-1
Scenario: You are tasked with writing a C program that accepts 5 integers from
the user, stores them in an array, and then displays them back in reverse order.

Task-2
Scenario: You are working on a program that allows the user to enter 6
temperatures for each day of the week. The user should also have the ability to
update a specific day’s temperature. After updating, display the entire week's
temperature.

Task-3
Scenario: Create a C program that accepts 6 integers from the user. The
program should allow the user to input an index and then display the value
stored at that index in the array.
Strings
■ Strings are the form of data used in programming
languages for storing an manipulating text such as
words, names, and sentences.
■ In C, a string is not a formal data type as it is in some
languages (e.g., Pascal, BASIC, VB, etc).
■ String is an array of type char.
■ All strings must end with a null character, ‘\0’, which
has a numerical value of 0.
String Variable
Example:
main()
{
char name[81];
printf(“ Enter your name: “);
scanf(“%s”,name);
printf(“Hello, %s. “,name);
getch();
}
Note:
Since a string name is an address, no address operator need
precede it in a scanf() function.
The String I/O Functions
There are many C functions whose purpose is to
manipulate strings. puts() and gets() are one of
them.
Example:
main()
{ char name[20];
puts(“ Enter your name: “);
gets(name);
puts(“Hello, “);
puts(name);
getch();
}
Using Character Arrays to Store and
Manipulate Strings
● We’ve discussed only integer arrays.
● However, arrays are capable of holding data of any type.
● We now discuss storing strings in character arrays. So
far, the only string-processing.
● A string such as "hello" is really an array of individual
characters in C.
■ Initializing a Character Array with a String
Initializing a Character Array with an
Initializer List of Characters
■ Character arrays also can be initialized with
individual character constants in an initializer
list, but this can be tedious. The preceding
definition is equivalent to
Arrays (Cont’d)
Characters Array or Strings

A string constant is a one-dimensional array


of characters terminated by a null (‘\0’).
The terminator define end of string.
For example,
char name[5] = { ‘F’, ‘A’, ‘S’, ‘T’, ‘\0’ };
Example
Arrays (Cont’d)
■ Input function scanf() can be used with %s
format specifier to read a string input from
the terminal. But there is one problem with
scanf() function, it terminates its input on
the first white space it encounters.
Therefore if you try to read an input string
"Hello World" using scanf() function, it will
only read Hello and terminate after
encountering white spaces.
Arrays (Cont’d)
The String I/O Function gets() & puts()
Scanf() and printf() is not versatile for string I/O we can use
gets() and puts() function from stdio.h library.
For Example:
Example
Scenario 1: Reverse a String
Problem Statement: Write a C program that
takes a string as input and prints its reverse.
The program should use a 1D character array
(string) to store the input and then display the
reversed string.
Scenario 2: Count Vowels in a String

Problem Statement: Write a C program that reads a


string from the user and counts the number of vowels
(a, e, i, o, u) in the string.

Use a 1D character array to store the input string.


String Functions

The string functions provide the ability to


manipulate string variables and literals. String
functions behave similarly to the standard C
language functions. The return values also
follow the C language convention. Most of
the commons are giving in next slides.
String Functions
strlen() for string length
strcpy() for copying one string to another
strcat() for concatenating strings
strcmp() for comparing two strings
strchr() for finding the first occurrence of a
character
strstr() for finding a substring in a string
Multiple-Subscripted Arrays

■ Multiple subscripted arrays


❑ Tables with rows and columns (m by n array)
❑ Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3


Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays (cont’d)

■ Initialization
1 2
❑ int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4
❑ Initializers grouped by row in braces
❑ If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

■ Referencing elements 1 0
3 4
❑ Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Multiple-Subscripted Arrays (cont’d)

■ Initializing 3-Dimentional Arrays:


int arr[3][2][4] =
{ { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 }, },
{ { 8, 7, 6, 5 },
{ 0, 2, 1, 4 }, },
{ { 8, 6, 6, 1 },
{ 1, 3, 5, 7 }, }, };
■ This is an array of arrays of arrays.
■ We could say, value at
arr[1][1][3] => 1 is true.
Syntax of 2D Array in C

Here,
size1: Size of the first dimension.
size2: Size of the second dimension.
2-D Array Example
Multiple-Subscripted Arrays (cont’d)
Task-4

1st Column
■ Write a program to change the case of all the
alphabets in an array of strings.

2nd Column
■ Write a program that counts the no. of upper
and lower case letters in an array of strings
Matrix Addition
Scenario: You are given two matrices
representing the sales data of two different
products over the same time period. Each
matrix has dimensions 3 X 3. Write a C
program to perform the addition of these two
matrices and display the resulting matrix.
Task5 - Matrix Multiplication
How to store user input data into 1D array
How to store user input data into 2D array
Important
Increment operator (++) - Array
It is used to increment the value of a variable by 1
There two types of increment operators − pre increment
and post increment.
Increment operator is placed before the operand in
preincrement and the value is first incremented and then
operation is performed on it.
Exercise

■ Write a C program to read through an array of any


type. Write a C program to scan through this array to
find a particular value.
■ Write a program to copy the contents of one array
into another in the reverse order.
■ Write a program to pick up the largest number from
any 5 row by 5 column matrix.
■ Write a program to add two 6 * 6 matrices.
■ Write a program to delete all vowels from a
sentence. Assume that the sentence is not more
than 80 characters long.
End of Week 10

Any Questions ?????

You might also like