-3

So i am just starting to learn c programming and i decided to practice by making my program speak to the end-user by asking questions and reacting to them

I first applied if-else statement for the program to react on the age of the person. then, when i get to the whats your favorite color part with the switch statements it would just close upon pressing any button.

My code:

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <ctype.h>

 main()
 {

 char name[25], c;
 int a;
 clrscr();

 printf("Hello, whats your name? \n");
 scanf("%s",name); 
 printf("nice to meet you %s!!!\n");

 printf("Whats your age?");
 scanf("%d",&a");
     {
      if((a <= 21) && (a >= 0))
        printf("Young!\n");

      else if((a <= 100) && (a >= 22))
       printf("old!\n");

      else
       printf("that's not an age!\n");
     }

printf("whats your favorite color? \n"); //this is where the program stops//
scanf("%c",&c);
  switch(tolower(c)){
    case 'r':printf("Fiery!");break;
    case 'o':printf("oranggerrr!!");break;  
     .
     . //basically applied the whole rainbow and put some reactions// 
     .

getch();
return 0;
}
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Mirisu
  • 3
  • 4

1 Answers1

0

Ok, so I compiled the program online here, making some changes, as the program you have given only compiles in the old Turbo C.

I compiled the following program:

#include <stdio.h>
//#include <conio.h>
//#include <dos.h>
#include <ctype.h>

 main()
 {

 char name[25], c;
 int a;
 //clrscr();

 printf("Hello, whats your name? \n");
 scanf("%s",name); //still dont get why it worked without the "&"//
 printf("nice to meet you %s!!!\n");

 printf("Whats your age?");
 scanf("%d",&a);
     {
      if((a <= 21) && (a >= 0))
        printf("Young!\n");

      else if((a <= 100) && (a >= 22))
       printf("old!\n");

      else
       printf("that's not an age!\n");
     }

printf("whats your favorite color? \n"); //this is where the program stops//
scanf("%c",&c);
  switch(c){
    case 'r':printf("Fiery!");break;
    case 'o':printf("oranggerrr!!");break;  
    // .
     //. //basically applied the whole rainbow and put some reactions// 
     //.
  }

getchar();
return 0;
}

Okay, so when I executed it, I got a segmentation fault, because of this line:

printf ("nice to meet you %s!!!\n");

to

printf ("nice to meet you %s!!!\n", name);

Then everything worked perfectly.

Now your doubt:

  • scanf ("%s", name); That works because name is a char array, and the name of an array is equal to the address of the first element in that array. Check this comment. Also, you can see the question.

Improvements:

  • Change scanf ("%c", &c); to scanf (" %c", &c);

NOTE: I cannot exactly reproduce your problem as I do not have Turbo C. Also, maybe your program crashed because of tolower. Note that tolower return the changed char, so you will have to do: c = tolower (c);

Community
  • 1
  • 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67