Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to C, and I want to iterate through a char array inputted by the user, and print a different predefined variable depending on which letter the loop is currently on.

Right now I have:
C
printf("Please enter your name: ");
scanf("%20[0-9a-zA-Z ]", nameVal);
printf("\n");

for (i = 0; nameVal[i] != '\0'; i++) {


What would my if statement look like?

I basically want to say "if the current letter in nameVal is "a", print char A"

Thanks in advance.
Posted

1 solution

Well, you could try:
C++
for (i = 0; nameVal[i] != '\0'; i++) 
   {
   if (nameVal[i] == 'a') printf("A");
   if (nameVal[i] == 'b') printf("B");
...
   }
Or better:
C#
for (i = 0; nameVal[i] != '\0'; i++)
   {
   switch(nameVal[i])
      {
      case 'a':
         printf("A");
         break;
      case 'b':
         printf("B");
         break;
...
      }
   }

But...this may be better:
C#
for (i = 0; nameVal[i] != '\0'; i++)
   {
   if ((nameVal[i] >= 'a') && (nameVal[i] <= 'z'))
       printf("%c", nameVal[i] + ('A' - 'a'));
   }
 
Share this answer
 
Comments
CPallini 14-Sep-15 3:52am    
5.
shanewignall 14-Sep-15 5:23am    
Thanks so much! I finally finished my first real C program with your help!
OriginalGriff 14-Sep-15 5:44am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900