Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
switch conditions in c programming

in switch case if I give option as 'aa' it prints a+b instead of it does not print default condition.why it accepting 'aa' as option?

    #include <stdio.h>

    int main() {
      int a=10,b=20;
      char ch;

      scanf("%c",&ch);

      switch(ch) {
          case 'a':
            printf("%d",a+b);
            break;
          case 'b':
            printf("%d",a*b);
          default:
            printf("thank u");
      }
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Char is represented in memory with 1 byte. If you want an string, like 'aaa', in memory we have 3 characters with one byte => 3 * 1 = 3 bytes. We represent this with an array. Like char string[200], here we have char * 200.

When you try to read 'aaa' from stdin in char, you read first character from stdin, because you don't allocate memory for all characters.

Try to print in stdout 'ch'. After you put scanf("%c", &ch), put printf("%c", ch); and will print first character from stdin.

#include <stdio.h>

int main() {
  int a=10,b=20;
  char ch; // One character

  scanf("%c",&ch); // Read one character, if we read 'aaa', ch is equal with 'a' beacause we read first one character from stdin.

  switch(ch) { //here ch is equal with one character.
      case 'a':
        printf("%d",a+b);
        break;
      case 'b':
        printf("%d",a*b);
      default:
        printf("thank u");
  }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!