"supposed to count all characters equal to A in a table ..but it doesn't work I need help to find the Problem !!"
Compiler warnings will help you to find the problem.
If you are not seeing warnings when you compile, set your compiler to show them. (in GCC for example use -Wall
)
When compiling with warnings turned on you should see information similar to this upon a compile:
Build Status (so.prj - Debug)
s0_15.c - 3 warnings
22, 22 warning: using the result of an assignment as a condition without parentheses
22, 22 note: place parentheses around the assignment to silence this warning
22, 22 note: use '==' to turn this assignment into an equality comparison
7, 17 warning: unused variable 'A'
14, 14 warning: variable 'i' is uninitialized when used here
8, 10 note: initialize the variable 'i' to silence this warning
Additionally, when dropping down into the second for()
loop, i
again is not initialized, but left with the value it had when finishing the first loop. It needs to be re-initialized to zero for that second loop to work... (Note, my compiler did not flag this, fortunately I was told at one point to learn how to set and use breakpoints which I did here, allowing me to discover the value of i
during runtime.
By following the guidance offered by the warnings above, modifications were made to allow the code to run, and does what you describe it should.
See comments in-line for the response to the warnings above:
int main(void)//added void to match accepted prototype of main
{
char T[100] = {0},A;//A is not used, should be deleted
//initialize array to all zeros.
int i=0,N=0,b=0;//initialized i (and N)
printf("give the number of your table's columns \n");
scanf("%d", &N);
if (N > 0 && N <= 100) {
for (i; i < N; i++) {
scanf("%c", &T[i]);
printf("give the character of the column number %d \n", i);
scanf("%c",&T[i]);
}
// `i` is already equal to N here. it will never enter the loop
//for (i; i < N; i++) {
for (i = 0; i < N; i++) {//initialized i to zero
//if (T[i] = 'A') b++;//this is not what you want
if (T[i] == 'A') b++; //replace assignment '='
//with comparison '==' operator
//Note, optionally move the following printf() statement to below
//the loop so it is called only once after counting is done.
printf("the number of characters equal to A is %d\n",b);//added '\n' for readability of output.
}
//return 0;// not here...
}
return 0;// ...but here
}