Sunteți pe pagina 1din 116

U18CSI1202

PROBLEM SOLVING AND PROGRAMMING USING C


Course Name:PROBLEM SOLVING AND PROGRAMMING USING C
Course Number: U18CSI1202
Credits: 3
Pre-requisite: Nil

Course Description:
This course is aimed at enabling the students to

·  Formulate simple algorithms for arithmetic and logical problems


·  Translate the algorithms to programs (in C language)
·  Write, execute and test the programs .
·  Implement conditional branching, iteration and recursion
·  Decompose a problem into functions and synthesize a complete program using divide
and conquer approach
·  Use arrays, pointers and structures to formulate algorithms and programs
·  Apply programming to solve matrix problems, searching and sorting problems 
Apply programming to solve simple numerical method problems, namely root finding,
differentiation of function and simple integration
Learning Objectives
• After undergoing this course the student able
to
COs

CO1 Acquire knowledge on different problem solving techniques.


CO2 Use appropriate data types and control structures for solving a given problem.
CO3 Execute different array and string operations.
CO4 Experiment with the usage of pointers and functions.
CO5 Organize data using structures and unions.
Source of Content
• https://courses.edx.org/dashboard
• https://www.khanacademy.org/
• https://www.youtube.com/watch?v=h-HBipu_1P0
• https://ocw.mit.edu/courses/electrical-engineerin
g-and-computer-science/6-s096-effective-program
ming-in-c-and-c-january-iap-2014/
• https://ocw.mit.edu/courses/electrical-
engineering-and-computer-science/6-087-
practical-programming-in-c-january-iap-
2010/lecture-notes/
Grading

CAT (2 Exams each 25%) 50%

10 Assignments (1% at each) 10%

End semester exam 40%

Total 100%
Lecture Notes
UNIT II
ARRAYS AND STRINGS
Learning Objectives
• Practicing the array concept to solve the
problems
• Memory allocation for 1D, 2D ...arrays
• Know about the storage of strings.
• Practicing how to deal with strings.
Arrays in C

Source: Multiple Educational


Resources from Internet
ARRAYS
 An array is a collection of elements of the same type that are
referenced by a common name.
 Compared to the basic data type (int, float & char) it is an
aggregate or derived data type.
 All the elements of an array occupy a set of contiguous memory
locations.
 Why do we need to use array type?
 Consider the following issue:

"We have a list of 1000 students' marks of an integer type. If


using the basic data type (int), we will declare something like the
following…"

int  studMark0, studMark1, studMark2, ..., studMark999;

int studmark[1000]
ARRAYS
 By using an array, we just declare like this,

int  studMark[1000];

 This will reserve 1000 contiguous memory locations for storing the
students’ marks.
 Graphically, this can be depicted as in the following figure.
ARRAYS
 Simplified our declaration of the variables.
 Use index or subscript to identify each element
 For example, studMark[0] will refer to the first element of
the array.
 Subscrpits varies from 0 to number of items in the array -1
 In an array declaration int a[10] will hold 10 integer data
items/ values and can be accessed using a[0]…a[9].
 a is known as base address. Address of the first item in an
array.
 Address of second item is a+1; here a+1 will be
automatically incremented depending on the data type of
the array.
 Note: Not to change the base address in the program ie. a.
ARRAYS
One Dimensional Array: Declaration

 A single or one dimensional array declaration has the


following form,

array_element_data_type array_name[array_size];

 array_element_data_type define the base type of the array,


which is the type of each element in the array.
 array_name is any valid C identifier name that obeys the
same rule for the identifier naming.
 array_size defines how many elements that the array can
hold.
ARRAYS
 For example, to declare an array of 30 characters,
char   cName[30];

 The array cName can store up to 30


characters with the first character occupying
the location cName[0] and the last character
occupying cName[29]. 
 Note that the index runs from 0 to 29.  In C,
an index always starts from 0 and ends with
(array's size-1).
 So, take note the difference between the
array size and subscript/index terms.
ARRAYS
 Examples of the one-dimensional array declarations,

int      xNum[20], yNum[50];
float    fPrice[10], fYield;
char     chLetter[70];

 The first example declares two arrays named xNum and yNum of type int. 
Array xNum can store up to 20 integer numbers while yNum can store up to
50 numbers. 
 The second line declares the array fPrice of type float.  It can store up to 10
floating-point values.
 fYield is basic variable which shows array type can be declared together
with basic type provided the type is similar.
 The third line declares the array chLetter of type char.  It can store a string
with up to 69 characters.
 Why 69 instead of 70? Remember, a string has a null terminating character
(\0) at the end, so we must reserve for it.
ARRAYS
Array Initialization
 An array may be initialized at the time of declaration.
 Giving initial values to an array.
 Initialization of an array may take the following form:
type   array_name[size] = {a_list_of_value};
 For example:
int    idNum[7] = {1, 2, 3, 4, 5, 6, 7}; // idNum[0]=1, idNum[1]=2
int a[4] = { 1,2}; // a[0]=1,a[1]=2,a[2]=0,a[3]=0
float  ft[3] = {5.6, 5.7, 5.8};// 5.6 to ft [0],  5.7  to  ft[1]
char   chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
 Assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so
on.  Note again, for characters we must use the single
apostrophe/quote (') to enclose them.
 Also, the last character in chVowel is NULL character ('\0').
ARRAYS
 Initialization of an array of type char for holding strings
may take the following form,
char    array_name[size] = "string_literal_constant";

 For example, the array chVowel in the previous


example could have been written more compactly as
follows,
char    chVowel[6] = "aeiou";

 When the value assigned to a character array is a string


(which must be enclosed in double quotes), the compiler
automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.
 For unsized array (variable sized), we can declare as
follows,
char chName[ ] = “Student";

 C compiler automatically creates an array which is big


enough to hold all the initializer.
Array Elements
• Array elements are commonly used in loops
• E.g.,
for(i=0; i < max; i++)
A[i] = i*i;

sum = 0; for(j=0; j < max; j++)


sum += B[j];

for (count=0;rc!=EOF;count++)
rc=scanf("%f", &A[count]);
Caution! Caution! Caution!
• It is the programmer’s responsibility to avoid
indexing off the end of an array
• Likely to corrupt data
• May cause a segmentation fault
• Could expose system to a security vulnerability!
• C does NOT check array bounds
• I.e., whether index points to an element within the
array
• Might be high (beyond the end) or negative (before the
array starts)
ARRAYS
Two Dimensional/2D Arrays

 A two dimensional array has two subscripts/indexes. 


 The first subscript refers to the row, and the second, to the column.
 Its declaration has the following form,

data_type    array_name[1st dimension size][2nd dimension size];

 For examples,

int      xInteger[3][4];
float    matrixNum[20][25];

 The first line declares xInteger as an integer array with 3 rows and 4
columns.
 Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.

ARRAYS
If we assign initial string values for the 2D array it will look
something like the following,
char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole",
"Kidman", "Arnold", "Jodie"};

 The array with 6 strings, each with maximum 9 characters long.


 If depicted in rows and columns as contiguous arrangement in
the memory.
ARRAYS
 Take note that for strings the null character (\0) still needed.
 For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square.

 The array size is = First index x second index = xy.


 This also true for other array dimension, for example three dimensional
array,

array_name[x][y][z]; => First index x second index x third index = xyz

 For example,

ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
Arrays Address = 1000

1 2 3
• int a[2][3] = { 1,2,3,4,5,6}; 4 5 6

• Array stored in memory like Address Data


in row major order 1000 1
1004 2
Column Major Order ?? 1008 3
100b 4
100f 5
1013 6
Array Declaration and Passing to
functions
Declaring Arrays
• Static or automatic
• Array size determined explicitly or implicitly
• Array size may be determined at run-time
Automatic only
Data Allocation
0xFFFFFFFF

stack
(dynamically allocated)

SP
Static
array
when s allo
progr cated h
a m is ere
loade
d.
heap
address space (dynamically allocated)

static data

program code PC
(text)
0x00000000
Data Allocation
Auto
matic
here arra
upon ys alloca
block entry ted
.
0xFFFFFFFF
to
stack
(dynamically allocated)
SP

heap
address space (dynamically allocated)

static data

program code PC
(text)
0x00000000
Dynamic Array Size Determination
• gcc supports the following:–
void func(<other parameters>, const int n) {
double Arr[2*n];

} //func

• i.e., array size is determined by evaluating


an expression at run-time
• Automatic allocation on The Stack
• Not in C88 ANSI standard
• Part of C99
Implicit Array Size Determination
• intdays[]={31,28,31,30,31,30,31,31,30,31,30,31};
– Array is created with as many elements as initial
values
• In this case, 12 elements
– Values must be compile-time constants (for static
arrays)
– Values may be run-time expressions (for
automatic arrays)
Getting Size of Implicit Array
• operator – returns # of bytes of
sizeof

memory required by operand


• Examples:–
• sizeof (int) – # of bytes per int
• sizeof (float) – # of bytes per float
• sizeof days – # of bytes in array days (previous
slide)

• # of elements in days = (sizeof


days)/sizeof(int)
Passing Arrays to Functions
• Passing arrays
– To pass an array argument to a function, specify the
name of the array without any brackets
– int myArray[ 24 ]; //myFunction(myArray, 24 );
• Array size usually passed to function
– Arrays passed using call-by-reference, Name of array is
address of first element
– Function knows where the array is stored
• Modifies original memory locations
• Passing array elements : Passed by call-by-value
– Pass subscripted variable (i.e., myArray[ 3 ]) to
function
Arrays: Sorting and Searching

& Multidimensional Array Example


Sorting Arrays
• Sorting data
– Important computing application
– Every organization must sort some kinds of data
• 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
Sorting Arrays
• Example: (Ascending Order)
– original: array a[5] is = { 1 4 3 8 7 } N=5.
1. First compare 1&4, since a[0]  a[1]
1<4 no swap. Array is if a[0]>a[1] then { swap a[0] and a[1]}
14387 else no need to swap
2. Then compare 4&3, since 4<3 a[1]  a[2]
swap 4&3 will get the array as if a[1]>a[2] then { swap a[1] and a[2]}
13487 else no need to swap
3. Compare 4&8, no swap a[2]  a[3]
13487 if a[2]>a[3] then { swap a[2] and a[3]}
else no need to swap
4. Compare 8&7, need swap. a[3]  a[4]
So, final array is if a[3]>a[4] then { swap a[3] and a[4]}
1 3 4 78 else no need to swap
Merge all these steps with a for loop ???
int i;
for(i=0,i<N-2;i++)
{ if a[i] > a[i+1] swap a[i] with a[i+1] }
Sorting
What is the outcome of all these comparisons??
This is known as Pass 1.
Second pass varies from 0 to N-3
Third pass varies from 0 to N-2.

How many passes needed??


Case Study: Computing Mean,
Median and Mode Using Arrays
• Mean – average
• Median – number in middle of sorted list
– 1, 2, 3, 4, 5
– 3 is the median
• Mode – number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5
– 1 is the mode
1 /*
2 This program introduces the topic of survey data analysis.
3 It computes the mean, median, and mode of the data */
4 #include <stdio.h>
5 #define SIZE 99
6 1. Function
7 void mean( const int [] ); prototypes
8 void median( int [] );
9 void mode( int [], const int [] ) ;
10 void bubbleSort( int [] );
11 void printArray( const int [] );
12
13 int main()
14 {
15 int frequency[ 10 ] = { 0 };
16 int response[ SIZE ] =
17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 1.1 Initialize array
20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
26 4, 5, 6, 1, 6, 5, 7, 8, 7 };
27
28 mean( response );
2. Call functions
29 median( response );
30 mode( frequency, response );
mean, median, and
31 return 0; mode
32 }
33
34 void mean( const int answer[] )
35 {
36 int j, total = 0;
37 3. Define function
38 printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); mean
39
40 for ( j = 0; j <= SIZE - 1; j++ )
41 total += answer[ j ];
42
43 printf( "The mean is the average value of the data\n"
44 "items. The mean is equal to the total of\n"
45 "all the data items divided by the number\n"
46 "of data items ( %d ). The mean value for\n"
47 "this run is: %d / %d = %.4f\n\n",
48 SIZE, total, SIZE, ( double ) total / SIZE );
49 }
50
51 void median( int answer[] )
52 {
3.1 Define
53 printf( "\n%s\n%s\n%s\n%s",
54 "********", " Median", "********", function median
55 "The unsorted array of responses is" );
56
57 printArray( answer );
58 bubbleSort( answer );
3.1.1 Sort Array
59 printf( "\n\nThe sorted array is" );
60 printArray( answer ); 3.1.2 Print middle
61 printf( "\n\nThe median is element %d of\n"
element
62 "the sorted %d element array.\n"
63 "For this run the median is %d\n\n",
64 SIZE / 2, SIZE, answer[ SIZE / 2 ] );
65 }
66
67 void mode( int freq[], const int answer[] )
68 {
3.2 Define
69 int rating, j, h, largest = 0, modeValue = 0;
70
function mode
71 printf( "\n%s\n%s\n%s\n",
72 "********", " Mode", "********" );
73
74 for ( rating = 1; rating <= 9; rating++ )
75 freq[ rating ] = 0;
76 Notice how the subscript in
77 for ( j = 0; j <= SIZE - 1; j++ ) frequency[] is the value of an
78 ++freq[ answer[ j ] ]; element in response[]
79 (answer[])
80 printf( "%s%11s%19s\n", 3.2.1 Increase
81 "Response", "Frequency", "Histogram", frequency[]
depending on
83
response[]
84 for ( rating = 1; rating <= 9; rating++ ) {
85 printf( "%8d%11d ", rating, freq[ rating ] );
86
87 if ( freq[ rating ] > largest ) {
88 largest = freq[ rating ];
89 modeValue = rating;
90 }
91 Print stars depending on value of
92 for ( h = 1; h <= freq[ rating ]; h++ ) frequency[]
93 printf( "*" );
94
95 printf( "\n" );
96 }
97
98 printf( "The mode is the most frequent value.\n"
99 "For this run the mode is %d which occurred"
100 " %d times.\n", modeValue, largest );
101 }
102
103 void bubbleSort( int a[] )
104 { Define bubbleSort
105 int pass, j, hold;
106
107 for ( pass = 1; pass <= SIZE - 1; pass++ )
108
109 for ( j = 0; j <= SIZE - 2; j++ )
110
111 if ( a[ j ] > a[ j + 1 ] ) {
112 hold = a[ j ];
113 a[ j ] = a[ j + 1 ]; Bubble sort: if elements out of
114 a[ j + 1 ] = hold; order, swap them.
115 }
116 }
117
118 void printArray( const int a[] ) Define printArray
119 {
120 int j;
121
122 for ( j = 0; j <= SIZE - 1; j++ ) {
123
124 if ( j % 20 == 0 )
125 printf( "\n" );
126
127 printf( "%2d", a[ j ] );
128 }
129 } Program Output
********
Mean
********
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788
 
********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
 
The sorted array is
1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
 
The median is element 49 of
the sorted 99 element array.
For this run the median is 7
********
Mode
********
Response Frequency Histogram
 
Program Output
 
1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.
Searching Arrays: Linear Search
• Search an array for a key value ( value to be
searched)
• Linear search
– Simple
– Starting from first element, compare each element
of the array with key value until the final array
element is compared.
– Useful for small and unsorted arrays
Searching Arrays: Binary Search
• Binary search
– For sorted arrays
– Compares middle element with key
• If equal, match found
• If key < middle, looks in first half of array
• If key > middle, looks in last half
• Repeat
– Very fast; at most n steps, where 2n > number of
elements
• 30 element array takes at most 5 steps
– 25 > 30 so at most 5 steps
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
• Initialization 1
3
2
4

– int b[ 2 ][ 2 ] = { { 1, 2 }, { 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
3
0
4
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
MULTIDIMENSIONAL ARRAY
1 /*
2 Double-subscripted array example */
3 #include <stdio.h>
4 #define STUDENTS 3
5 #define EXAMS 4 1. Initialize
6 variables
7 int minimum( const int [][ EXAMS ], int, int );
8 int maximum( const int [][ EXAMS ], int, int );
9 double average( const int [], int );
1.1 Define
10 void printArray( const int [][ EXAMS ], int, int ); functions to take
Each row is a particular
double scripted
11
12 int main()
student, each column is the
arrays
13 { grades on the exam.
14 int student;
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
16 { { 77, 68, 86, 73 },
17 { 96, 87, 89, 78 },
18 { 70, 90, 86, 81 } };
19
1.2 Initialize
20 printf( "The array is:\n" ); studentgrades[][]
21 printArray( studentGrades, STUDENTS, EXAMS );
22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
2. Call functions
23 minimum( studentGrades, STUDENTS, EXAMS ),
24 maximum( studentGrades, STUDENTS, EXAMS ) );
minimum, maximum,
25 and average
26 for ( student = 0; student <= STUDENTS - 1; student++ )
27 printf( "The average grade for student %d is %.2f\n",
28 student,
29 average( studentGrades[ student ], EXAMS ) );
30
31 return 0;
32 }
33
34 /* Find the minimum grade */
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 { 3. Define functions
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 double average( const int setOfGrades[], int tests )
64 {
65 int i, total = 0;
66
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69 3. Define functions
70 return ( double ) total / tests;
71 }
72
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
77 int i, j;
78
79 printf( " [0] [1] [2] [3]" );
80
81 for ( i = 0; i <= pupils - 1; i++ ) {
82 printf( "\nstudentGrades[%d] ", i );
83
84 for ( j = 0; j <= tests - 1; j++ )
85 printf( "%-5d", grades[ i ][ j ] );
86 }
87 }
The array is:
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
Program Output
studentGrades[2] 70 90 86 81

Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
Arrays and Matrices in C

Source: Educational Resources from


the internet
Matrices (2D-array)

• A matrix is a set of numbers arranged in a grid with rows and columns.


• A matrix is defined using a type declaration statement.
– datatype array_name[row_size][column_size]; 4

– int matrix[3][4]; 1
0

Row 0 4 1 0 2 2
-1

Row 1 -1 2 4 3 2
4

Row 2 0 -1 3 1 3
0
-1
3

Column 0Column 1Column 2Colum


1

n3 memory – row major order

54
Accessing Array Elements
int matrix[3][4];
• matrix has 12 integer elements
• matrix[0][0] element in first row, first
column
• matrix[2][3] element in last row, last
column
• matrix is the address of the first element
• matrix[1] is the address of the Row 1
• matrix[1] is a one dimensional array (Row
55
1)
Initialization
int x[4][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
int x[][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
56
Initialization

int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;

matrix[i][j] = j;
j
j
0 1 2 3 0 1 2 3
0 0 0 0 0
0 0 1 2 3
i 1 1 1 1
1 i 0 1 2 3
1
2 2 2 2 2
2 0 1 2 3

57
Exercise
• Write the nested loop to initialize a 2D array
as follow

0 1 2 int i, j, x[4][3];
1 2 3 for(i=0; i<4; i++)
2 3 4 for(j=0; j<3; j++)
3 4 5 x[i][j] = i+j;

58
2-Dim Arrays as Arguments to Functions

void print_m(int m[3][4],


int r, int c)

void print_m(int m[][4],


int i, j, matrix[3][4]; int r, int c)
{
for (i=0; i<3; i++) int i,j;
for (j=0; j<4; j++) for (i=0; i < r; i++) {
matrix[i][j] = i; for (j=0; j < c; j++)
printf("%5d ",m[i][j]);
print_m(matrix, 3, 4); printf("\n");
}
printf("\n");
return;
}

59
Computations on 2D arrays

60
Max in 2D
• Find the maximum of (positive)
int matrix[3][4]

int max =0; 0 1 2 3


0 0 1 0 2
for (i=0; i<3; i++)
for (j=0; j<4; j++) 1 1 2 4 3
if (matrix[i][j] > max) 2 0 1 3 1
max = matrix[i][j];

61
Find a value in 2D

• Find the number of times x appears in int matrix[3][4]

int count = 0; 0 1 2 3
0 0 1 0 2
for (i=0; i<3; i++)
for (j=0; j<4; j++) 1 -1 2 4 3
if (matrix[i][j] == x) 2 0 -1 3 1
count = count + 1;

62
Matrix sum

• Compute the addition of two


matrices
0 1 2 3 0 1 2 3 0 1 2 3
0 0 1 0 2 0 3 -1 3 1 0 3 0 3 3
-1 2 4 3 + 1 1 4 2 0 = 1 0 6 6 3
1
2 0 -1 3 1 2 2 1 1 3 2 2 0 4 4

63
solution
int matrix1[3][4],
matrix2[3][4],
sum[3][4];
// initialize matrix1 and matrix2

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


for (j=0; j<4; j++)
sum[i][j]= matrix1[i][j]+matrix2[i][j];

64
Transpose
void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS])
{
a /* Declare Variables. */
1 5 3 int i, j;
4 2 6
/* Transfer values to the
transpose matrix. */
b for(i=0; i<NROWS; i++) {
1 4 for(j=0; j<NCOLS; j++) {
b[j][i] = a[i][j];
5 2 }
}
3 6 return;
}

65
Matrix multiplication
double a[3][2], b[2][4], c[3][4];
• Find c = a * b;
• a= 1 2 3
4 5 6

• b= 4 5
6 7
8 9

c[0][0] = a[0][0]*b[0][0] + a[0][1]*b[1][0] + a[0][2]*b[2] [0]


c[0][1] = a[0][0]*b[0][1]+ a[0][1]*b[1][1] + a[0][2]*b[2][1]
c[1][0] = a[1][0]*b[0][0] + a[1][1]*b[1][0] + a[1][2] *b[2][0]
c[1][1] = a[1][0]*b[0][1] + a[1][1]*b[1][1] + a[1][2]*b[2][1]
66
Matrix Multiplication cont’d

j
j 0 1 2 3
0 1 2 3 22 29 45 35
0 3 4 2 3 7 1
0

1 5 2 x = 1 18 40 47 21
4 5 6 8 2
2 1 6 26 33 43 49
i i
j=0
c[i][j] =
2
i=0 3 4 x k = a[i][k=0]*b[k=0][j] +
4 a[i][k=1]*b[k=1][j]
k

67
Matrix Multiplication cont’d

#define N 3
#define M 2
#define L 4
void matrix_mul(a[N][M], int b[M][L], int c[N][L])
{
int i, j, k;
for(i=0; i < N; i++) {
for(j=0; j < L; j++) {
c[i][j] = 0;
for(k=0; k < M; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return;
}

68
Strings in C

Source: Educational Resources from


Internet
Character Strings
• A sequence of characters is referred to as a character
“string”.
• A string is stored in an array of type char ending with
the null character '\0 '.
Character Strings
A string containing a single character takes up 2
bytes of storage.
Character Strings
Character Strings
Character vs. String

• A string constant is a sequence of characters


enclosed in double quotes.
– For example, the character string:

char s1[2]="a"; //Takes two bytes of


storage.
s1:
a \0
– On the other hand, the character, in single quotes:

char s2= `a`; //Takes only one byte


of storage.
a
s2:
Character vs. String
Strings
• A special kind of array is an array of characters ending in the null
character \0 called string arrays

• A string is declared as an array of characters


• char s[10]
• char p[30]

• When declaring a string don’t forget to leave a space for the null
character which is also known as the string terminator character
C offers four main operations on strings

• strcpy - copy one string into another


• strcat - append one string onto the right side
of the other
• strcmp – compare alphabetic order of two
strings
• strlen – return the length of a string
strcpy
• strcpy(destinationstring, sourcestring)
• Copies sourcestring into destinationstring

• For example
• strcpy(str, “hello world”); assigns “hello world”
to the string str, where str is the character
array or character pointer.
Example with strcpy
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “Example with strcpy”;
char y[25];
printf(“The string in array x is %s \n “, x);
strcpy(y,x);
printf(“The string in array y is %s \n “, y);
}
strcat
• strcat(destinationstring, sourcestring)

• appends sourcestring to right hand side of destinationstring

• For example if str had value “a big ”


• strcat(str, “hello world”); appends “hello world” to the string “a big ” to
get
• “ a big hello world”
Example with strcat
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “Example with strcat”;
char y[]= “which stands for string concatenation”;
printf(“The string in array x is %s \n “, x);
strcat(x,y);
printf(“The string in array x is %s \n “, x);

}
strcmp
• strcmp(stringa, stringb)

• Compares stringa and stringb alphabetically


• Returns a negative value if stringa precedes stringb alphabetically
• Returns a positive value if stringb precedes stringa alphabetically
• Returns 0 if they are equal
• Note: lowercase characters are greater than Uppercase
• Compares the ASCII value of the characters.
• ASCII value of a,b, ..., z = 97,98,...,122 and for A,B, ..., Z = 65,66,...,90
Example with strcmp
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “cat”;
char y[]= “cat”;
char z[]= “dog”;
if (strcmp(x,y) == 0)
printf(“The string in array x %s is equal to that in %s \n “, x,y);
continued
if (strcmp(x,z) != 0)
{printf(“The string in array x %s is not equal to that in z %s \n “,
x,z);
if (strcmp(x,z) < 0)
printf(“The string in array x %s precedes that in z %s \n “, x,z);
else
printf(“The string in array z %s precedes that in x %s \n “, z,x);
}
else
printf( “they are equal”);
}
strncpy() and strncat()
Function prototype Function description
char *strcpy( char *s1, Copies string s2 into array s1. The value of s1 is
const char *s2 ) returned.
char *strncpy( char *s1, Copies at most n characters of string s2 into array s1.
const char *s2, size_t n ) The value of s1 is returned.
char *strcat( char *s1, Appends string s2 to array s1. The first character of
const char *s2 ) s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1, Appends at most n characters of string s2 to array s1.
const char *s2, size_t n ) The first character of s2 overwrites the terminating
null character of s1. The value of s1 is returned.
1 /* Fig. 8.19: fig08_19.c
2
3
Using strcat and strncat */
#include <stdio.h> • Strcat vs
4 #include <string.h>
5
6 int main()
strncat
7 {
8 char s1[ 20 ] = "Happy ";
9 char s2[] = "New Year ";
10 char s3[ 40 ] = "";
11
12 printf( "s1 = %s\ns2 = %s\n", s1, s2 );
13 printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) );
14 printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) );

15 printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) );


16 return 0;
17 }

s1 = Happy
s2 = New Year
strcat( s1, s2 ) = Happy New Year
strncat( s3, s1, 6 ) = Happy
strcat( s3, s1 ) = Happy Happy New Year
strcmp() vs strncmp()
int strcmp( const char *s1, const char *s2 );

– Compares string s1 to s2
– Returns a negative number if s1 < s2, zero if s1
== s2 or a positive number if s1 > s2
int strncmp( const char *s1, const char *s2, size_t n );

– Compares up to n characters of string s1 to s2


– Returns values as above
strlen
• strlen(str) returns length of string excluding
null character
• strlen(“tttt”) = 4 not 5 since \0 not counted
Example with strlen
#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if (x[i] == ‘t’) count++;
}
printf(“The number of t’s in %s is %d \n “, x,count);

}
Vowels Example with strlen
#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘a’)||(x[i]==‘e’)||(x[i]==‘i’)||(x[i]==‘o’)||(x[i]==‘u’)) count++;
}
printf(“The number of vowels’s in %s is %d \n “, x,count);

}
No of Words Example with strlen

#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘ ‘) count++;
}
printf(“The number of words’s in %s is %d \n “, x,count+1);

}
No of Words Example with more than one space
between words
#include <stdio.h>
#include <string.h>
main()
{
int i,j, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘ ‘)
{ count++;
for(j=i;x[j] != ‘ ‘;j++);
i = j;
}
}
printf(“The number of words’s in %s is %d \n “, x,count+1);

}
Input output functions of characters and strings

• getchar() reads a character from the keyboard


in a non-interactive environment
• putchar(int ch) outputs a character to screen
• gets(str) gets a string from the keyboard
• puts(str) outputs string to screen
Characters are at the heart of strings
Exercise 1

Output
1
12
123
1234
………….
1 2 3 4 5 6 7 8 9 10
Exercise 1
#include <stdio.h>
main()
{
int i,j;
for(j = 1; j <= 10; j++)
{
for(i=1;i <= j;i++)
{
printf(“%d “,i);
}
printf(“\n“);
}
}
Exercise 2

Output
*
**
***
****
…………….
**********
Exercise 2
#include <stdio.h>
main()
{
int i,j;
for(j = 1; j <= 10; j++)
{
for(i=1;i <= j;i++)
{
printf(“* “);
}
printf(“\n“);
}
}
Some Useful C Character Functions

• Don't forget to #include <ctype.h> to get the


function prototypes.
Functions
• Function Return true if
• int isalpha(c); c is a letter.
• int isupper(c); c is an upper case
letter.
• int islower(c); c is a lower case letter.
• int isdigit(c); c is a digit [0-9].
More Functions
• Function Return true if
• int isxdigit(c); c is a hexadecimal digit
[0-9A-Fa-f].
• int isalnum(c); c is an alphanumeric character (c is a letter or a
digit);
• int isspace(c); c is a SPACE, TAB, RETURN, NEWLINE,
FORMFEED, or vertical tab character.
Even More C Functions
• Function Return true if
• int ispunct(c); c is a punctuation
character (neither control
nor alphanumeric).
• int isprint(c); c is a printing character.
• int iscntrl(c); c is a delete character or
ordinary control character.
Still More C Functions
• Function Return true if
• int isascii(c); c is an ASCII character,
code less than 0200.
• int toupper(int c); convert character c to
upper case (leave it
alone if not lower)
• int tolower(int c); convert character c to
lower case (leave it
alone if not upper)
Strings in C
Input, Output &
Array of Strings

Source: Educational Resources from


Internet
String Input
• Use %s field specification in scanf to read string
– ignores leading white space
– reads characters until next white space encountered
– C stores null (\0) char after last non-white space char
– Reads into an array
• Example:
char Name[11];
scanf(“%s”,Name);
• Problem: no limit on number of characters
read (need one for delimiter), if too many
characters for array, problems may occur
String Input (cont)
• Can use the width value in the field
specification to limit the number of characters
read:
char Name[11];
scanf(“%10s”,Name);
• Remember, you need one space for the \0
– width should be one less than size of array
• Strings shorter than the field specification are
read normally, but C always stops after reading
10 characters
String Input (cont)
• Edit set input %[ListofChars]
– ListofChars specifies set of characters (called scan set)
– Characters read as long as character falls in scan set
– Stops when first non scan set character encountered
– Note, does not ignore leading white space
– Any character may be specified except ]
– Putting ^ at the start to negate the set (any character BUT list is
allowed)
• Examples:
scanf(“%[-+0123456789]”,Number);
scanf(“%[^\n]”,Line); /* read until newline char */
String Output
• Use %s field specification in printf:
characters in string printed until \0 encountered
char Name[10] = “Rich”;
printf(“|%s|”,Name); /* outputs |Rich| */
• Can use width value to print string in space:
printf(“|%10s|”,Name); /* outputs | Rich| */
• Use - flag to left justify:
printf(“|%-10s|”,Name); /* outputs |Rich | */
Reading a Whole Line
char *gets(char *str)
• reads the next line (up to the next newline) from keyboard
and stores it in the array of chars pointed to by str
• returns str if string read or NULL if problem/end-of-file
• not limited in how many chars read (may read too many for
array)
• newline included in string read

char *fgets(char *str, int size, FILE *fp)


• reads next line from file connected to fp, stores string in str
• fp must be an input connection
• reads at most size characters -1 from stream and stores in
buffer pointed to by str ( \0 is stored as the last char in buffer)
• returns str if string read or NULL if problem/end-of-file
• to read from keyboard: fgets(mystring,100,stdin)
• newline included in string read
Printing a String

int puts(char *str)


• prints the string pointed to by str to the screen
• prints until delimiter reached (string better have a \0)
• returns EOF if the puts fails
• outputs newline if \n encountered (for strings read with gets
or fgets)
int fputs(char *str, FILE *fp)
• prints the string pointed to by str to the file connected to fp
• fp must be an output connection
• returns EOF if the fputs fails
• outputs newline if \n encountered
fgets/fputs Example
#include <stdio.h>
void main() {
char fname[81];
char buffer[101];
FILE *instream;
printf("Show file: ");
scanf("%80s",fname);
if ((instream = fopen(fname,"r")) == NULL) {
printf("Unable to open file %s\n",fname);
exit(-1);
}
fgets/fputs Example (cont)
printf("\n%s:\n",fname);

while (fgets(buffer,sizeof(buffer)-1,instream)
!= NULL)
fputs(buffer,stdout);

fclose(instream);
}
Printing to a String
The sprintf function allows us to print to a string
argument using printf formatting rules
First argument of sprintf is string to print to,
remaining arguments are as in printf
Example:
char buffer[100];
sprintf(buffer,”%s, %s”,LastName,FirstName);
if (strlen(buffer) > 15)
printf(“Long name %s %s\n”,FirstName,LastName);
Reading from a String
The sscanf function allows us to read from a
string argument using scanf rules
First argument of sscanf is string to read from,
remaining arguments are as in scanf
Example:
char buffer[100] = “A10 50.0”;
sscanf(buffer,”%c%d%f”,&ch,&inum,&fnum);
/* puts ‘A’ in ch, 10 in inum and 50.0 in fnum */
Array of Strings
• Sometimes useful to have an array of string
values
• Each string could be of different length
• Example:
char *MonthNames[13]; /* an array of 13 strings */
MonthNames[1] = “January”; // String with 8 chars
MonthNames[2] = “February”; // String with 9 chars
MonthNames[3] = “March”; // String with 6 chars
etc.
Array of Strings Example
#include <stdio.h>

void main() {
char *days[7];
char TheDay[10];
int day;

days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";

S-ar putea să vă placă și