C/array
Expert: Smitha Renny - 9/19/2009
QuestionQUESTION: Good dAy!!i'm a freshman student of i.t here in the Philippines..
i would like to know what condition would i have if im going to have a program that will store ten names and will ask any user for his name. if his/her name is in the array it will print "hi friend", if not "excuse me stranger"..Im confused on how will i declare and what would be the condition for me to have the right output..hope you can help me ouT.
thanks!!
ANSWER: Hi Isheen Kae
For this situation the normal thing would be to think of an array of names.
But 'C' in its original self does not have a data type for strings. So we work around this problem by declaring an array of characters for a single name and then an array of 10 such names. That should solve our problem. Although C does not have a ready-made data type for strings, it does have functions(strcmp()) with which we can compare entire strings. These functions will help us in the comparison part of our problem. So then the code for this would look like this:
#include <stdio.h>
#include <string.h>
void main(){
char names[30][10]; //we are declaring a 2-dimensional array of characters, we
//are also assuming that each name will not have more than
//29 char, reserving the last char for \0
char chk_name[30];
int i;
printf("Enter 10 names");
for(i=0;i<10;++i)
scanf("%[^\n]",&names[i]); // accepting the 10 names from the user
printf("Enter the name to be checked in the list");
scanf("%[^\n]",chk_name);
for(i=0;i<10;++i){
if(!strcmpi(names[i],chk_name)){ //strcmpi() compares (lexicographically) the two
//strings given to it as arguments and returns 0 if
//they are identical. It is not case sensitive.
printf("Hi Friend !");}
else
printf("Excuse me stranger !");
}
}
Hope this is helful to you. Do let me know (in a follow-up) in case you need any further clarifications.
Warm Regards
Smitha Renny
---------- FOLLOW-UP ----------
QUESTION: thank yOu but what i mean would be that i the array would alredy have ten names and only the user name will be typed..how can i assign ten names?
AnswerHi Isheen Kae
That is simpler still. You'll have to provide the char array the values at the time of declaration itself. The following is the code:
#include <stdio.h>
#include <string.h>
void main(){
char names[][10]={"TOM","SAM","JON","PAM","NICK","PAT","JACK","JILL","CHRIS","JEFF"};
//we are declaring a 2-dimensional
//array of characters,providing it
//the values
char chk_name[30];
int i;
printf("Enter the name to be checked in the list");
scanf("%[^\n]",chk_name);
for(i=0;i<10;++i){
if(!strcmpi(names[i],chk_name)){ //strcmpi() compares (lexicographically) the two
//strings given to it as arguments and returns 0 if
//they are identical. It is not case sensitive.
printf("Hi Friend !");}
else
printf("Excuse me stranger !");
}
}
Guess this would solve your problem.
Warm Regards
Smitha Renny