2. Arrays
• String is array of characters
• char a[10];
• strcpy(a,”kamakoti”);
• equivalent to
• a[0] = ‘k’; a[1] = ‘a’; … a[7] = ‘i’;
a[8] = ‘0’
3. Arrays
• You can’t assign
– a = “kamakoti”;
– Except at time of declaration
• char a[] = kamakoti
• When you would like to use string commands
inside the program
– #include <string.h>
• Other commands
– strlen() - Number of characters preceding NULL
– strcat(a,b) - Concats the string “b” to “a”.
6. Other Arrays
•
•
•
•
•
•
•
•
int A[100];
Can store 100 integers in sequence.
Let int be 4 bytes
A[0] is stored in 100 - 103
A[1] is stored in 104 - 107
A[2] is stored in 108 - 111
….
A[i] is stored in (100 + i*4) - (100 + i*4 + 3)
7. Other Arrays
• This implies given where A[0] is stored
say B, you can compute where A[j] is
stored.
– (B + i*sizeof(int)) - (B+ i*sizeof(int) + sizeof(int)-1)
• Extend it for double A[100]
– (B + i*sizeof(double)) - (B+ i*sizeof(double) + sizeof(double)-1)
12. Creative Exercise – 5
The Celebrity problem
0
0
0
0
0
0
0
0
Celebrity is a person who is known to everyone but
does not know anyone. To find a celebrity among “n”
people by questioning them. You can ask only one
type of question. You can ask person X whether he
knows Y.
13. Solution
• Take any two person A and B
• “Ask A if he knows B” - no one lies
– If yes then A is not a celebrity else B is not a
celebrity
– Every question eliminates one
– (n-1) questions eliminates n-1 person
– The left out person CAN be a Celebrity
– You need 2(n-1) questions more
– Total 3(n -1) questions.
14. Creative Problem
• Suppose you are using a program that
reads in a large English text file as input
and processes it. The program for some
reason does not like a set of words and
whenever it sees the same in your text
file it halts and outputs “Error”. It is so
angry that it does not say what the word
is and which line it occurred or any
other info.
15. Creative Problem
• You do not have a list of offending
words. Devise a strategy to identify the
first offending word in your text. Express
the efficiency of your strategy in terms
of the number of words in the input text
file.
16. Solution
• The input file T is indeed erroneous. The
program gives error on input file T
• Suppose the text file T has n = 2k words
• Split the text file T into two parts T1 and T2,
containing the first and the last n/2 words
respectively
• Give T1 to program (not T2 - why?)
– If error then the offending word is in T1; else in T2
17. Solution
• Assume offending word in T1
– Split T1 into T11 and T12 of n/4 words
each
– Give T11 to program
• If error then offending word in T11 else in T12
• Finally you will land up with a file with 2
words. Split them as one word each and
give them in order to the program to find
out the first offending word.