13

Click here to load reader

Lec12-CS110 Computational Engineering

Embed Size (px)

DESCRIPTION

A keynote on Problem Solving using Computers

Citation preview

Page 1: Lec12-CS110 Computational Engineering

CS110: Arrays in C

Lecture 12V. Kamakoti

4th February 2008

Page 2: Lec12-CS110 Computational Engineering

Loops

• for (j = 1; j <= 10; j++)– The initial and final conditions are known.– What if the final condition is not known– The other iterative structures in C are

• while and do-while

Page 3: Lec12-CS110 Computational Engineering

While

• while (condition) { statement; }• do { statement; } while (condition);• The difference

Page 4: Lec12-CS110 Computational Engineering

Lab Work

Theme: Strings

Page 5: Lec12-CS110 Computational Engineering

Problem - 1

• Length of a string– First enter string– Can use scanf() but there is a problem

• A string is any set of ASCII characters includingwhite space.

• Examples -• char myst[80]; /*myst is a pointer */• scanf(“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”,myst);• Input is New York, then it shall read only N.• scanf(“%[^\n]”,myst);

Page 6: Lec12-CS110 Computational Engineering

Continued

• We may use the gets() function.– char myst[80];– gets(myst);

• Defined in <stdio.h>• How are strings stored

– Array of characters– char myst[3] = “RED” /*An error */– myst[0] = ‘R’, myst[1] = ‘E’, myst[2] = ‘D’– myst[3] = ‘\0’;

Page 7: Lec12-CS110 Computational Engineering

Problem 1

• Declare a LONG character array– char myst[80];

• The user enters the string using scanf()or gets() statement.

• Now use a while loop to scan the arrayof characters “myst”, till you encounter‘\0’ and output the length of the string.

Page 8: Lec12-CS110 Computational Engineering

Problem 2

• Check for Palindrome• MALAYALAM - read it from L to R and

R to L - it reads the same• Unlike COMPUTER

– It reads RETUPMOC• The easy way is shown in next slide

Page 9: Lec12-CS110 Computational Engineering

Problem 2

• char myst[80], tmpst[80];• Find length of the string• Copy the string myst[] in reverse order

using a for loop into tmpst[]• Compare character by character myst[]

and tmpst[]• Same is true for Problem 3, reversing a

string

Page 10: Lec12-CS110 Computational Engineering

What is needed

• Slightly complicated• Use the same string mystr[]• Do not use tmpstr[]• Keep comparing from end to end for

palindrome and swapping from end toend for reversal

Page 11: Lec12-CS110 Computational Engineering

Example

• M A L A Y A L A M• ODD and EVEN length - Take care• Reversal• C O M P U T E R• R O M P U T E C• R E M P U T O C• R E T P U M O C• R E T U P M O C - Answer

Page 12: Lec12-CS110 Computational Engineering

Creative Exercise

• I have a blackbox that takes as inputtwo symmetric matrices and outputs itsproduct. How can I use it to multiply twoarbitrary matrices.

Page 13: Lec12-CS110 Computational Engineering

Thank You