Click here to load reader
Upload
sriharsha-p
View
33
Download
0
Embed Size (px)
DESCRIPTION
A keynote on Problem Solving using Computers
Citation preview
CS110: Arrays in C
Lecture 12V. Kamakoti
4th February 2008
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
While
• while (condition) { statement; }• do { statement; } while (condition);• The difference
Lab Work
Theme: Strings
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);
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’;
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.
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
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
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
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
Creative Exercise
• I have a blackbox that takes as inputtwo symmetric matrices and outputs itsproduct. How can I use it to multiply twoarbitrary matrices.
Thank You