Home > Back-end >  Trouble with a C program
Trouble with a C program

Time:12-02

I had a homework. The condition was: "Make a program in witch will be displayed how many 'A' and 'B' where typed". I tried and this is what i made:

#include <stdio.h>

int main()
{
    int n, i, a=0, b=0;
    char cr;
    
    scanf ("%i", &n);
    
    for (i=0; i<=n; i  ) {scanf ("%c", &cr); if (cr='A') a  ; else if (cr=='B') b  ;}
    
    printf ("A-%i\n", a);
    printf ("B-%i", b);
}

The problem is when i type for example 10, it only lets me type 5 characters, not 10. Why? The program can be made with for, while or do while.

CodePudding user response:

Problems and solutions

  • you need to use scanf(" %c", %cr) to prevent the program from reading trailing whitespaces
  • You should be using if (cr == 'A') and not if (cr = 'A') because you are comparing and not assigning
  • the loop should be for (i = 0; i < n... not for (i = 0; i <= n.. as the loop would ask for 1 input from the specified range
#include <stdio.h>

int main() {
    int n, a = 0, b = 0;
    char cr;
    printf("Enter number of tries :\n");
    scanf ("%i", &n);
    for (int i = 0; i < n; i  ) {
        printf("Enter char\n");
        scanf(" %c", &cr); 
        if (cr == 'A') a  ; 
        else if (cr == 'B') b  ;
    }
    printf ("A-%i\n", a);
    printf ("B-%i", b);
}
  •  Tags:  
  • c
  • Related