C programming count number of occurrences? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am working though the C programming book. I have a question in the arrays section (1.6) that says "Let us write a program to count the number of occurrences of each digit, of white space characters (blank, tab, newline) and all other characters.
#include <stdio.h>
/* count digits, white space, others */
int main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; i++)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-0];
else if (c == ' ' || c == '\n' || c == '\t')
nwhite++;
else
nother++;
printf("digits =");
for (i = 0; i < 10; i++);
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
This is the compiling code. If I type 23, enter, 23, enter then ctrl+d it returns "digits = 1044509184, white space = 2, other = 0". Why? What is digits doing?

if (c >= '0' && c <= '9')
++ndigit[c-0];
This block of code is problematic as it is accessing the array out of bounds (and will cause undefined behaviours).
It should be
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
Notice the difference between 0 and '0'. The latter piece of code works as it is guaranteed that number characters are encoded consecutively.

Related

Problem using printf() to output the contents of an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have started working through "The C programming language, 2nd Ed." & already I'm running into problems. This code is from Chapter 1 on arrays,
#include <stdio.h>
int main(void){
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i){
ndigit[i] = 0;
}
while ((c = getchar()) != EOF){
if (c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
}
printf("digits =");
for (i = 0; i < 10; ++i){
printf(" %d", ndigit[i]);
}
printf(", white space = %d, other = %d\n", nwhite, nother);
}
It compiles (gcc via Visual Studio Code, Win 10, x64) no errors or warnings. I input the following sequence via the keyboard,
12333 45666 789
and the output I get,
digits = 0^C
Now I was expecting,
digits = 0 1 1 3 1 1 3 1 1 1, white space = 2, other = 0
I then rewrote the for loop that is supposed to print the array to print out i
for (i = 0; i < 10; ++i){
printf(" %d", i);
}
Then got,
digits = 0^C
What's going on here? First off, why isnt the array being printed, secondly why is the final printf() statement not being executed?
EDIT:: Thanks to the comments, I didn't understand the EOF character properly & how the input stream works. If I exit with ctrl+z and then enter the program executes correctly!

Word Count Program in C is not counting correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Like the title says im writing a Word Count clone Program in C, but is not counting correctly in one of the cases.
I have .txt file and the program works fine but if i use the following command
linux>./wordcountclone < file.txt
it only counts half the words.
Am i doing anything wrong?
if i use for example
linux>./wordcountclone file.txt
or
linux>./wordcountclone -l -d file.txt
works fine.
Here goes the function im using
void fileO(FILE * name, int car, int word, int lin, int dig){
int c , nl, np, nc, nd, state;
state = OUT;
nl = nc = nd = 0;
np = -1;
c = fgetc(name);
while (c != EOF){
c = fgetc(name);
nc++;
if(nc > INT_MAX)
return;
if (c == '\n')
nl++;
if (c > 47 && c < 58)
nd++;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
if (state == OUT) {
state = IN;
np++;
}
}
if(lin !=0)
printf("lines %d ", nl);
if(word != 0)
printf("words %d ", np);
if(dig !=0)
printf("digits %d ", nd);
if(car != 0)
printf("chars %d ", nc);
printf("\n");
}
and the .txt file that i am using has the following text
the cat sat on the mat
the dog jumped over the moon
At least 2 problems here:
You always skip the first char doing c = fgetc(name); twice in a row - one before while and then inside the loop.
The state logic is incorrect - if you run this on a file containing only whitespace it'll still count words.
Also, a couple of suggestions:
instead of if (c > 47 && c < 58) you could do if ('0' <= c && c <= '9') or use isdigit()
use isspace() to check for whitespace

My C arrays test program is not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am reading The C Programming Language 2nd Edition. I am doing the 2.10 in a tutorial introduction. I have to write a program about arrays. It is supposed to count digits, white spaces and others. This is the program:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d ", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
return 0;
}
According to the book, the output of the program by itself is
digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345
I have 2 questions:
How will the program output by itself without me doing the CTRL+Z?
When I do it manually the output is not right. Please see if I made a mistake in the code.
The output I get is
digits =, white space = 0, other = 0
This:
printf("digits =");
for (i = 0; i < 0; ++i)
printf(" %d ", ndigit[i]);
has a broken middle part in the for loop's header; i < 0 will not be true (ever!) so the loop will not run.
for (i = 0; i < 0; ++i)
This is wrong.

K&R code not working in VS2012 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is from K&R, it's supposed to count digits, white space, etc. I compile fine but when I run I just get a blank screen and all I can do is type inputs. Is this not working because the C language is outdated?
#include <stdio.h>
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
Well to put it simply. This loop will end once you type ctrl + d. If you want for it to end when you press enter, just modify it a bit: change
while ((c = getchar()) != EOF)
to
while ((c = getchar()) != '\n')
The program is written to get input until an end-of-file character. Since you're using DOS, enter Ctrl+Z to terminate input (you have to hit "enter" after the Ctrl+Z because keyboard input will be line-buffered).
On edit: Ctrl+Z is the end-of-file (EOF) character in the Windows/DOS world. In UNIX/Linux environments, it is (usually) Ctrl+D.

I dont know what is wrong with this program. it's supposed to convert binary to decimal in c [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
well this program is supposed to convert a binary number to decimal. im new to c and im not very confident in coding C. tried and coded this program but doesnt run properly. and I have no idea what part is wrong here. need some help to complete this program.
thanks
binaryToDecimal(char str[]) {
for(int i = strlen(str)-i; i>=0; i--) {
if(str[i] == 48 || str[i] == 49) {
int tmp = pow(2, counter);
int sum= str[i]*tmp;
counter++;
answer += sum;
} else if(str[i]>49 || str[i]<48) {
printf("error");
}
}
printf("%d", &answer);
}
This phrase doesn't make sense:
int i = strlen(str)-i;
i hasn't been initialized yet, but you're using it in the expression!
I believe you meant:
int i = strlen(str)-1; // ONE ... not I
str[i] is a character, either '1' or '0' which as you have it is equal to 48 and 49 as integers. So you want to convert them to 1 and 0 them do the multiplication.
sum = (str[i] - 48) * tmp;
Assuming all variables have been initialised to sensible values and str holds the input. The following code should work, although it is not particularly efficient.
You can use '0' and '1' instead of more obscure 48 and 49.
for (i = strlen(str)-1, j = 0; i >= 0; --i, ++j) {
if (str[i] != '0' && str[i] != '1') {
printf("ERROR: unxepected input\n");
exit(EXIT_FAILURE);
}
if (str[i] == '1')
sum += pow(2, j);
}
when printing the result provide the value and not it's address, e.g.
printf("%d\n", sum); // (!) not &sum

Resources