You are on page 1of 62

Day 1

1/1
CS1100 – Introduction to Programming



• Programming : From Turtle to C.




• Data Types in C, Operators. Input and the Output. 




• Modifying the control flow in Programs if-else, 

switch, loops : while, do-while, for. Week 1-6

• Implementing numerical methods using a




C-program. 



• (single-dimensional) Arrays in C. 


2/1
CS1100 – Introduction to Programming



• Programming : From Turtle to C.




• Data Types in C, Operators. Input and the Output. 




• Modifying the control flow in Programs if-else, 

switch, loops : while, do-while, for. Week 1-6

• Implementing numerical methods using a




C-program. 



• (single-dimensional) Arrays in C. 





• Strings, Multi-dimensional Arrays in C. Week 7

2/1
Character arrays

char name[20];

Different ways of initialization


• char name[20] = “Avani”;
• char name[20] = {‘A’, ‘V’, ‘A’, ‘N’, ‘I’, ’null char’};
• char name[20];
scanf(“%s”, name);

3/1
Character arrays

char name[20];

Different ways of initialization


• char name[20] = “Avani”;
• char name[20] = {‘A’, ‘V’, ‘A’, ‘N’, ‘I’, ’null char’};
• char name[20];
scanf(“%s”, name);
• char name[20];
name = ”AVANI”; Incorrect!!

3/1
What is the output of this program?

#include<stdio.h>
main() {
char name[20] = "AVANI";
int i;

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


name[i] = ’X’;
}

printf("name = %s\n", name);

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


printf("%c %d\n", name[i], name[i]);
}
}
4/1
Character arrays and standard library support

• Character arrays or strings occur very often.


• C provides a standard library string.h
• exposes several useful functions:
• strlen
• strcmp
• strcpy
• strstr
• But we can create libraries.

5/1
Example 1 : Finding the length of a given string

Task : Given a string at the input, find the length.

6/1
Example 1 : Finding the length of a given string

Task : Given a string at the input, find the length.


Pseudo-code :
for i ranging from 1 to n
• if you find that i th
character is null
character output i and
break.

6/1
Example 1 : Finding the length of a given string

Task : Given a string at the input, find the length.


Pseudo-code : Program Segment:
for i ranging from 1 to n char s[1000];
int i;
• if you find that i th scanf("%s", s);
character is null
character output i and for(i=0 ; s[i] != ’\0’; ++i);
break.
printf("Length : %d", i);

6/1
Example 2 : Compare two strings

Task : Given two strings s1, s2, check if s1 and s2 are the same.

7/1
Example 2 : Compare two strings

Task : Given two strings s1, s2, check if s1 and s2 are the same.
if (s1 == s2) This does not work

7/1
Example 2 : Compare two strings

Task : Given two strings s1, s2, check if s1 and s2 are the same.
if (s1 == s2) This does not work

Pseudo-code :
Find the length ` of the two
strings first. If they are differ-
ent, declare that the strings are
different.
For i ranging from 1 to `
• check if i th characters
are the same. If not,
declare NOT same.
Can we combine the two steps
above?
7/1
Example 2 : Compare two strings

Task : Given two strings s1, s2, check if s1 and s2 are the same.
if (s1 == s2) This does not work
Program Segment:
Pseudo-code :
Find the length ` of the two // strings are in arrays a and b
strings first. If they are differ- int i = 0;
ent, declare that the strings are
different. while (a[i] == b[i]){
if ((a[i] == ’\0’)||(b[i] == ’\0’))
For i ranging from 1 to ` break;
• check if i th characters i++;
}
are the same. If not,
declare NOT same. if (a[i] == ’\0’ && b[i] == ’\0’)
Can we combine the two steps printf("SAME");
else
above? printf("NOT SAME");
7/1
Example 3 : Palindromes

A string is a palindrome iff string == reverse(string)

8/1
Example 3 : Palindromes

A string is a palindrome iff string == reverse(string)

• malayalam
• neveroddoreven
• dontnod

8/1
Example 3 : Palindromes

A string is a palindrome iff string == reverse(string)

• malayalam
• neveroddoreven
• dontnod

Write a program to determine if the given string is a palindrome.

8/1
Example 3 : Palindromes

Task : Given a string check if it is a palindrome.

Pseudo-code :

• Run and index i from 1


to n and another j from
n to 1.
• check if i th character is
equal to j th character. If
not, declare NOT
PALINDROME.
• If all checks pass - then
declare PALINDROME.
• You can do better

9/1
Example 3 : Palindromes

Task : Given a string check if it is a palindrome.

Pseudo-code : Program Segment:

• Run and index i from 1 // string is in the array named str


to n and another j from int l = 0;
int h = strlen(str) - 1;
n to 1.
• check if i th character is while (h > l)
equal to j th
character. If {
if (str[l++] != str[h--])
not, declare NOT {
PALINDROME. printf("NOT PALINDROME");
• If all checks pass - then break;
}
declare PALINDROME. }
• You can do better printf("PALINDROME");
// spot the error
9/1
Largest element in an array

Task : Program to find the largest element in a given array.

10/1
Largest element in an array

Task : Program to find the largest element in a given array.


Program Segment :
int i;

// Initialize maximum element


int max = arr[0];

// Traverse array elements from second and


// compare every element with current max
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];

10/1
Sorting an array in decreasing order

Task : Given array of n (n ≤ 1000) numbers. Sort them in


decreasing order of numbers.

15 8 3 12 30 7 9 17 32 19

11/1
Sorting an array in decreasing order

Task : Given array of n (n ≤ 1000) numbers. Sort them in


decreasing order of numbers.

15 8 3 12 30 7 9 17 32 19

One possible way: An algorithm


• Find max, place it at first location.
• Sort the array from second location to end.
Called Selection Sort.

11/1
Selection sort

15 8 3 12 30 7 9 17 32 19

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19
32 30 3 12 8 7 9 17 15 19

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19
32 30 3 12 8 7 9 17 15 19
.. .. .. .. .. .. .. .. .. ..
. . . . . . . . . .
32 30 19 17 15 12 9 8 7 3

Pseudo-code :
• while (i ≤ n )
• maxindex = index of the max element in the part of the array
indexed from i to n. Find maxindex.

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19
32 30 3 12 8 7 9 17 15 19
.. .. .. .. .. .. .. .. .. ..
. . . . . . . . . .
32 30 19 17 15 12 9 8 7 3

Pseudo-code :
• while (i ≤ n )
• maxindex = index of the max element in the part of the array
indexed from i to n. Find maxindex. (We have solved this !!)

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19
32 30 3 12 8 7 9 17 15 19
.. .. .. .. .. .. .. .. .. ..
. . . . . . . . . .
32 30 19 17 15 12 9 8 7 3

Pseudo-code :
• while (i ≤ n )
• maxindex = index of the max element in the part of the array
indexed from i to n. Find maxindex. (We have solved this !!)
• swap elements array[i] and array[maxindex];

12/1
Selection sort

15 8 3 12 30 7 9 17 32 19
32 8 3 12 30 7 9 17 15 19
32 30 3 12 8 7 9 17 15 19
.. .. .. .. .. .. .. .. .. ..
. . . . . . . . . .
32 30 19 17 15 12 9 8 7 3

Pseudo-code :
• while (i ≤ n )
• maxindex = index of the max element in the part of the array
indexed from i to n. Find maxindex. (We have solved this !!)
• swap elements array[i] and array[maxindex]; (We have solved
this too !!)

12/1
Day 2

13/1
Selection sort - from the pseudocode to the program

Pseudo-code :
for i ranging from 1 to n
• maxindex = the index of
the max element in the
part of the array indexed
from i to n. Find
maxindex.
• swap elements array[i]
and array[maxindex];

14/1
Selection sort - from the pseudocode to the program

Program Segment:
Pseudo-code :
for (i=0; i<n; i++)
for i ranging from 1 to n {
• maxindex = the index of max = i;
for (j=i+1; j<n; j++)
the max element in the {
part of the array indexed if (a[j] > a[max])
from i to n. Find max = j;
maxindex. }
temp = a[i];
• swap elements array[i] a[i] = a[max];
and array[maxindex]; a[max] = temp;
}

14/1
Selection sort – number of comparisons

• Which input do we consider?

15/1
Selection sort – number of comparisons

• Which input do we consider?


• Do number of comparisons depend on the particular array
values?

15/1
Selection sort – number of comparisons

• Which input do we consider?


• Do number of comparisons depend on the particular array
values?
• How does the method perform when the array is nearly sorted?

15/1
Selection sort – number of comparisons

• Which input do we consider?


• Do number of comparisons depend on the particular array
values?
• How does the method perform when the array is nearly sorted?

• Consider a “worst-case” input.

15/1
Selection sort – number of comparisons

• Which input do we consider?


• Do number of comparisons depend on the particular array
values?
• How does the method perform when the array is nearly sorted?

• Consider a “worst-case” input.


• Irrespective of whether the array is sorted or not, the method
n(n−1)
always needs 2 comparisons.

15/1
Multi-dimensional arrays in C

• Declaring a multi-dimensional array


int myArray[size1][size2]. . . [sizeN];
int matrix [10][10];

16/1
Multi-dimensional arrays in C

• Declaring a multi-dimensional array


int myArray[size1][size2]. . . [sizeN];
int matrix [10][10];
• How is a two-dimensional array stored in memory?

16/1
Multi-dimensional arrays in C

• Declaring a multi-dimensional array


int myArray[size1][size2]. . . [sizeN];
int matrix [10][10];
• How is a two-dimensional array stored in memory?
• Initializing a two-dimensional array.

16/1
Multi-dimensional arrays in C

• Declaring a multi-dimensional array


int myArray[size1][size2]. . . [sizeN];
int matrix [10][10];
• How is a two-dimensional array stored in memory?
• Initializing a two-dimensional array.

#include<stdio.h>

main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}
}
16/1
Multi-dimensional arrays in C

• Accessing elements of the array : A[i][j] - element in row i


and column j of array A.

17/1
Multi-dimensional arrays in C

• Accessing elements of the array : A[i][j] - element in row i


and column j of array A.
• Rows/columns numbered from 0.

17/1
Multi-dimensional arrays in C

• Accessing elements of the array : A[i][j] - element in row i


and column j of array A.
• Rows/columns numbered from 0.
• Storage: row-major ordering elements of row 0, elements of
row 1, etc.

17/1
Multi-dimensional arrays in C

• Accessing elements of the array : A[i][j] - element in row i


and column j of array A.
• Rows/columns numbered from 0.
• Storage: row-major ordering elements of row 0, elements of
row 1, etc.

17/1
Initializing Multi-dimensional arrays

#include<stdio.h>

main() {
int matrix1[3][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};

int matrix2[][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};
}

18/1
Initializing Multi-dimensional arrays

#include<stdio.h>

main() {
int matrix1[3][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12}; • Cannot omit the
column size.

int matrix2[][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};
}

18/1
Initializing Multi-dimensional arrays
What does the program print?
/* Assume N1=3, N2=4 */
main() {
int matrix[N1][N2] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};

int i;
for (i = 0; i<N1; i++) {
printf("%d\n", matrix[i][2]++);
}

for (i = 0; i<N2; i++) {


printf("%d\t", matrix[2][i]);
}
printf("\n");
}
19/1
Reading/Writing matrices at the input

mat : name of the matrix


rows, cols : number of rows and columns.

20/1
Reading/Writing matrices at the input

mat : name of the matrix


rows, cols : number of rows and columns.
Reading Matrices from the input:
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);

20/1
Reading/Writing matrices at the input

mat : name of the matrix


rows, cols : number of rows and columns.
Reading Matrices from the input:
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);

Writing matrices to the output:


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++) /* print a row */
{ printf ("%d ", mat[i][j]); } /* notice missing \n */
printf ("\n"); /* print a newline at the end a row */
}

20/1
Matrix Operations : Addition
• Write a program to add two matrices A and B

21/1
Matrix Operations : Addition
• Write a program to add two matrices A and B

#include<stdio.h>
main() {

/* Assume N1 and N2 are defined as const int */

int A[N1][N2];
int B[N1][N2];
/*initialize A, B suitably */
int C[N1][N2];
int i, j;

for (i = 0; i<N1; i++) {


for (j = 0; j<N2; j++) {
A[i][j] = B[i][j] + C[i][j];
}
}
}
21/1
Matrix Operations : Multiplication
• Write a program to multiply matrices A and B

22/1
Matrix Operations : Multiplication
• Write a program to multiply matrices A and B

22/1
Matrix Operations : Multiplication
• Write a program to multiply matrices A and B

23/1
Matrix Operations : Multiplication
• Write a program to multiply matrices A and B

main() {

const int N1;


int A[N1][N1], B[N1][N1], C[N1][N1];
int i, j, k, sum;
/* Assume A, B are initialized suitably */

for (i = 0; i<N1; i++) {


for (j = 0; j<N1; j++) {
sum = 0;
for (k=0; k<N1; k++) {
/* fill in your code here */
}
C[i,j] = sum;
}
}
}
23/1
This week : Take Aways

• Technical: Learned about single, multidimensional arrays,


character arrays, strings. Declaration, Initialization, reading,
writing.
• Problem Solving : Writing programs to solve various tasks
associated where use of arrays, matrices, strings are natural.

24/1
This week : Take Aways

• Technical: Learned about single, multidimensional arrays,


character arrays, strings. Declaration, Initialization, reading,
writing.
• Problem Solving : Writing programs to solve various tasks
associated where use of arrays, matrices, strings are natural.
• Meta-level message about the approach : Writing
algorithms/pseudo-code/programs - identify simpler tasks
within the given task, solve them and and then try to combine
them to get the bigger solution. (Eg : using the code for
”finding largest in a subarray” to do ”sorting”)

24/1
This week : Take Aways

• Technical: Learned about single, multidimensional arrays,


character arrays, strings. Declaration, Initialization, reading,
writing.
• Problem Solving : Writing programs to solve various tasks
associated where use of arrays, matrices, strings are natural.
• Meta-level message about the approach : Writing
algorithms/pseudo-code/programs - identify simpler tasks
within the given task, solve them and and then try to combine
them to get the bigger solution. (Eg : using the code for
”finding largest in a subarray” to do ”sorting”)
• Observation: Subtasks that appear once solved, can be used
in several parts of the program.

24/1
This week : Take Aways

• Technical: Learned about single, multidimensional arrays,


character arrays, strings. Declaration, Initialization, reading,
writing.
• Problem Solving : Writing programs to solve various tasks
associated where use of arrays, matrices, strings are natural.
• Meta-level message about the approach : Writing
algorithms/pseudo-code/programs - identify simpler tasks
within the given task, solve them and and then try to combine
them to get the bigger solution. (Eg : using the code for
”finding largest in a subarray” to do ”sorting”)
• Observation: Subtasks that appear once solved, can be used
in several parts of the program. Functions !!

24/1

You might also like