K&R C Histogram - c

I'm currently doing exercise 1-13 in K&R's C the Programming Language 2nd edition. I decided to start with a simple histogram that just replaces each letter in a word with '*'.
#include <stdio.h>
// histogram
#define IN 1
#define OUT 0
main() {
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == '\n' || c == '\t' || c == ' ') {
state = OUT;
putchar('\n');
}
else {
if (c != '\n' || c != ' ' || c != '\t') {
state = IN;
putchar('*');
}
}
}
}
However, take a look at this snippet of code:
else {
if (c != '\n' || c != ' ' || c != '\t') {
state = IN;
putchar('*');
}
}
How come this works, but if I enter if (state != OUT) , it doesn't work? I end up getting a completely different output. Aren't those two statements essentially the same thing?

c being equal to three terms "or" each other is not equivalent c not being equal to the negations of the same three terms "or" each other.
See De Morgan's laws.

Related

C Programming Language 2nd edition exercise 1-12 question

Why the below condition:
if (c !=' ' && c !='\t' && c !='\n')
matches either:
not space + not \n - when input is "abc \n"
or
not \t + not \n - when input is "abc\t\n"
When AND logical operator is used?
Should not AND require to match all conditions the same time?
Not space + NOT \t + NOT \n
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main() {
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c !=' ' && c !='\t' && c !='\n')
{
printf("%c", c);
state = IN;
}
else if (state)
{
printf("\n");
state = OUT;
}
}
}
You seem to be confused regarding what the condition is actually checking for.
This condition:
if (c !=' ' && c !='\t' && c !='\n')
Written out as English, says: "if c is not a space AND c is not a tab AND c is not a newline".
In other words, the condition is true when c matches none of those 3 characters.
It is working as intended, test it with vertical-tab.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main() {
int c, state;
state = OUT;
while ( (c = getchar()) != EOF) {
if (c != ' ' && c != '\t' && c != '\n') {
printf ("%c", c);
state = IN;
} else if (state) {
printf ("\v");
state = OUT;
}
}
return 0;
}
space, newline & tab chars are ignored and after every word we print a vertical-tab. We see this step pattern to prove that.
There are tabs in 2nd edition
./a.out
C Programming Language 2nd edition exercise 1-12 question
C
Programming
Language
2nd
edition
exercise
1-12
question

Substituting the next character from a stream of characters in a while loop

I'm supposed to design a program that count the number of words, so this is part of my code
while ((c=getc(file)) != EOF)
{ if ((isspace(c) || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v')) { ++word; } }
The logic of my code should first look at the first character if it was non-space, then it should look at the following if it was space then it should count one word
However, I know how to substitute the current character (in my code) but I don't know how to substitute the following character?
Basically, I want to write my code in this logic form (c+ is the character that follows c)
while ((c=getc(file)) != EOF)
{ if ( c is non-space)
{ if (c+ is space)
{ word++ }
}
}
prevC = ' ';
while ((c=getc(file)) != EOF)
{
if ((prevC != ' ') &&
(isspace(c) || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'))
{
++word;
}
prevC = c;
}
You need to maintain previous character that was read and compare it in the next iteration

Count lines , words, characters in C

This code is taken from C Programming by K & R. I am newbie to C programming and i need little help in understanding this code. This code gives me error please help me how to fix it
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n') ++nl;
if (c == ' ' || c == '\n' || c = '\t') state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
Error :
E:\Files\C\main.c:5:1: warning: return type defaults to 'int' [-Wreturn-type]
E:\Files\C\main.c: In function 'main':
E:\Files\C\main.c:14:40: error: lvalue required as left operand of assignment
E:\Files\C\main.c:21:1: warning: control reaches end of non-void function [-Wreturn-type]
You are assigning the value for c instead of comparing.
if (c == ' ' || c == '\n' || c = '\t') state = OUT;
should be
if (c == ' ' || c == '\n' || c == '\t') state = OUT;
And your main function should be like int main(void) and put a return 0 at the end
you are assigning value rather than comparing it:if (c == ' ' || c == '\n' || c = '\t'), == is used for comparison and = is used for assignment.
first of all change main function to int main() at line 5.
Also at line 13 try to use == for making it equal in the way shown below.
if (c == ' ' || c == '\n' || c == '\t') state = out;
//you assign a value instead
Also to terminate a program, at the end write return 0;

Character, Line and Word Counter in C [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 8 years ago.
Improve this question
I am sorry to ask so many questions but I am clueless what to do when my Program gives me errors which I don't understand how to fix. I use Code Blocks. The book name is The C Programming Language 2nd Edition.
The Code:
#include <stdio.h>
#include <stdlib.h>
#define IN 1
#define OUT 0
int main()
{
int c, nl, nw, nc, state;
state = OUT;
while((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
if (c == '' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d \n", nl, nw, nc);
}
So when I build it it gives me error on line 14 saying:
||=== Build: Debug in Line Counter v2 (compiler: GNU GCC Compiler) ===|
C:\Users\Uddhava\Desktop\Uddhava\Learning\Programming\C C+\Line Counter v2\
main.c|14|error: empty character constant|
C:\Users\Uddhava\Desktop\Uddhava\Learning\Programming\C C+\Line Counter v2\
main.c|14|error: lvalue required as left operand of assignment|
||=== Build failed: 2 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
if (c == '' || c == '\n' || c = '\t')
The first thing wrong with this line is that it should be:
if (c == ' ' || c == '\n' || c == '\t')
if (c == '' || c == '\n' || c = '\t')
should be
if (c == ' ' || c == '\n' || c == '\t')
if (c == '\n')
if (c == '' || c == '\n' || c = '\t')
In your code, the first if statement makes the second meaningless.
You are testing the value of c against an empty character constant '', which is not allowed. I think you want to test it against a space ' '.
If you want to test the value of your variable c with an empty space, you should compare it with ' ' instead of ''. Furthermore, comparison operator is ==, not = (assignment), which you used to compare the tab character '\t' in the last condition of your if statement, thus your if statement should be:
if (c == ' ' || c == '\n' || c == '\t')
this code block:
while((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
if (c == '' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
does not indicate (via the indentation) exactly which 'if' clause
is related to the 'else clause.
this is a VERY good reason to include ALL the '{' and '}' braces
this is what is actually written in the code:
while((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
{
if (c == '' || c == '\n' || c = '\t') // two errors on this line
{
state = OUT;
}
else if (state == OUT)
{
state = IN;
++nw;
}
}
}
the question becomes: is this what you really wanted?
we already know that the code is not correct
because the second 'if' will ALWAYS fail due to 'c' being
already confirmed as containing a '\n'
and the comparison of 'c' to ''
and the assignment of '\t' to 'c'
therefore, I suspect it should be:
while((c = getchar()) != EOF)
{
++nc;
if (('\n' == c) || (' ' == c) || ('\n' == c) || ('\t' == c) )
{
state = OUT;
}
else if (state == OUT)
{
state = IN;
++nw;
}
}
which would have also caught the assignment of '\t' to c at compile time
rather than you having to spend many an hour debugging the code.
I.E. put the literal on the left side of the comparison operator '=='
Well this worked, I used ideas from Amadeus, user3629249 and Min Fu. Thanks everyone for your help.
Working Code:
#include <stdio.h>
#include <stdlib.h>
#define IN 1
#define OUT 0
int main()
{
int c, nl, nw, nc, state;
state = OUT;
nc = 0;
nl = 0;
nw = 0;
while((c = getchar()) != EOF)
{
++nc;
if (('\n' == c) || (' ' == c) || ('\n' == c) || ('\t' == c) )
{
state = OUT;
++nl;
}
else if (state == OUT)
{
state = IN;
++nw;
}
}
printf("%d %d %d \n", nl, nw, nc);
return 0;
}

K&R Exercise 1-9 (C)

"Write a program to copy its input to
its output, replacing each string of
one or more blanks by a single blank."
I'm assuming by this he means input something like...
We(blank)(blank)(blank)go(blank)to(blank)(blank)(blank)the(blank)mall!
... and output it like:
We(blank)go(blank)to(blank)the(blank)mall!
This is probably easier than I'm making it out to be, but still, I can't seem to figure it out. I don't really want the code... more so pseudo code.
Also, how should I be looking at this? I'm pretty sure whatever program I write is going to need at least one variable, a while loop, a couple if statements, and will use both the getchar() and putchar() functions... but besides that I'm at a loss. I don't really have a programmers train of thought yet, so if you could give me some advice as to how I should be looking at "problems" in general that'd be awesome.
(And please don't bring up else, I haven't got that far in the book so right now that's out of my scope.)
Look at your program as a machine that moves between different states as it iterates over the input.
It reads the input one character at a time. If it sees anything other than a blank, it just prints the character it sees. If it sees a blank, it shifts to a different state. In that state, it prints one blank, and then doesn't print blanks if it sees them. Then, it continues reading the input, but ignores all blanks it sees--until it hits a character that isn't a blank, at which point it shifts back to the first state.
(This concept is called a finite state machine, by the way, and a lot of theoretical computer science work has gone into what they can and can't do. Wikipedia can tell you more, though in perhaps more complicated detail than you're looking for. ;))
Pseudo code
while c = getchar:
if c is blank:
c = getchar until c is not blank
print blank
print c
C
You can substitute use of isblank here if you desire. It is unspecified what characters contrive blank, or what blank value is to be printed in place of others.
After many points made by Matthew in the comments below, this version, and the one containing isblank are the same.
int c;
while ((c = getchar()) != EOF) {
if (c == ' ') {
while ((c = getchar()) == ' ');
putchar(' ');
if (c == EOF) break;
}
putchar(c);
}
Since relational operators in C produce integer values 1 or 0 (as explained earlier in the book), the logical expression "current character non-blank or previous character non-blank" can be simulated with integer arithmetic resulting in a shorter (if somewhat cryptic) code:
int c, p = EOF;
while ((c = getchar()) != EOF) {
if ((c != ' ') + (p != ' ') > 0) putchar(c);
p = c;
}
Variable p is initialized with EOF so that it has a valid non-blank value during the very first comparison.
This is what I got:
while ch = getchar()
if ch != ' '
putchar(ch)
if ch == ' '
if last_seen_ch != ch
putchar(ch)
last_seen_ch = ch
Same explanation with Matt Joiner's, but this code does not use break.
int c;
while ((c = getchar()) != EOF)
{
if (c == ' ') /* find a blank */
{
putchar(' '); /* print the first blank */
while ((c = getchar()) == ' ') /* look for succeeding blanks then… */
; /* do nothing */
}
if (c != EOF) /* We might get an EOF from the inner while-loop above */
putchar(c);
}
I worked really hard at finding a solution that used only the material that has already been covered in the first part of the first chapter of the book. Here is my result:
#include <stdio.h>
/* Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. */
main()
{
int c;
while ((c = getchar()) != EOF){
if (c == ' '){
putchar(c);
while ((c = getchar()) == ' ')
;
}
if(c != ' ')
putchar(c);
}
}
Here is how I think of the algorithm of this exercise, in pseudo-code:
define ch and bl (where bl is initially defined to be 0)
while ch is = to getchar() which is not = to end of file
do the following:
if ch is = to blank and bl is = 0
--> output ch and assign the value 1 to bl
else --> if ch is = to blank and bl is = 1
--> do nothing
else --> output ch and assign the value 0 to bl
Example implementation in C:
#include <stdio.h>
#include <stdlib.h>
main() {
long ch,bl=0;
while ((ch=getchar()) != EOF)
{
if (ch == ' ' && bl == 0)
{
putchar(ch);
bl=1;
} else if (ch == ' ' && bl == 1) {
// no-op
} else {
putchar(ch);
bl=0;
}
}
return 0;
}
I wrote this and seems to be working.
# include <stdio.h>
int main ()
{
int c,lastc;
lastc=0;
while ((c=getchar()) != EOF)
if (((c==' ')+ (lastc==' '))<2)
putchar(c), lastc=c;
}
#include <stdio.h>
int main()
{
int c;
while( (c = getchar( )) != EOF )
{
if (c == ' ')
{
while ((c = getchar()) == ' ');
putchar(' ');
putchar(c);
}
else
putchar(c);
}
return 0;
}
#include <stdio.h>
main()
{
int c, numBlank=0 ;
while((c= getchar())!=EOF)
{
if(c ==' ')
{
numBlank ++;
if(numBlank <2)
{
printf("character is:%c\n",c);
}
}
else
{
printf("character is:%c\n",c);
numBlank =0;
}
}
}
First declare two variables character and last_character as integers.when you have not reach the end of the file( while(character=getchar() != EOF ) do this;
1. If character != ' ' then
print character
last_character = character
2. If character == ' '
if last_character ==' '
last character = character
else print character
Using the constraints of not using else or and operators. This code only prints a blank when the blank variable is equal to 1 and the only way to reset the counter is by typing something other than a blank. Hope this helps:
include
/* Write a program that replaces strings of blanks with a single blank */
void main(){
int c, bl;
bl = 0;
while((c = getchar()) != EOF){
if(c == ' '){
++bl;
if(bl == 1){
putchar(' ');
}
}
if(c != ' '){
putchar(c);
bl = 0;
}
}
}
Many others have already used the last character logic in their code, but perhaps the following version is easier to read:
int c, prevchar;
while ((c = getchar()) != EOF) {
if (!(c == ' ' && prevchar == ' ')) {
putchar(c);
prevchar = c;
}
}
#include <stdio.h>
main() {
int input, last = EOF;
while ((input = getchar()) != EOF) {
if (input == ' ' && last == ' ') continue;
last = input;
putchar(input);
}
}
I am at the same point in the book. and my solution goes with making a count++ if blank is found and making the count back to zero if anything other than blank is found.
For if statement I put another another check to check value of count (if zero) and then print.
Though at this point of learning I shouldn't be concern about efficiency of two methods but which one is efficient a.) Accepted solution here with while inside while or b.) the one I suggested above.
My code goes like below:
#include <stdio.h>
main()
{
int count=0,c;
for( ; (c=getchar())!=EOF; )
{
if(c==' ')
{
if(count==0)
{
putchar(c);
count++;
}
}
if(c!=' ')
{
putchar(c);
count=0;
}
}
}
#include <stdio.h>
main()
{
int CurrentChar, LastChar;
LastChar = '1';
while ((CurrentChar = getchar()) != EOF)
{
if (CurrentChar != ' ')
{
putchar(CurrentChar);
LastChar = '1';
}
else
{
if (LastChar != ' ')
{
putchar(CurrentChar);
LastChar = ' ';
}
}
}
}
a way to make it easier for the new people are stuck on this book
(by not knowing any thing then what brought up until page 22 in K&R).
credits to #Michael , #Mat and #Matthew to help me to understand
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) /* state of "an input is not EOF" (1) */
{
if (c == ' ') /* "blank has found" -> change the rule now */
{
while ((c = getchar ()) == ' '); /* as long you see blanks just print for it a blank until rule is broken (2) */
putchar(' ');
}
putchar(c); /* either state (2) was broken or in state (1) no blanks has been found */
}
}
1.Count the number of blanks.
2.Replace the counted number of blanks by a single one.
3.Print the characters one by one.
<code>
main()
{
int c, count;
count = 0;
while ((c = getchar()) != EOF)
{
if (c == ' ')
{
count++;
if (count > 1)
{
putchar ('\b');
putchar (' ');
}
else putchar (' ');
}
else
{
putchar (c);
count = 0;
}
}
return;
}
</code>
#include <stdio.h>
int main(void)
{
long c;
long nb = 0;
while((c = getchar()) != EOF) {
if(c == ' ' || c == '\t') {
++nb;
} else {
if(nb > 0) {
putchar(' ');
nb = 0;
}
putchar(c);
}
}
return 0;
}
To do this using only while loops and if statements, the trick is to add a variable which remembers the previous character.
Loop, reading one character at a time, until EOF:
If the current character IS NOT a space:
Output current character
If the current character IS a space:
If the previous character WAS NOT a space:
Output a space
Set previous character to current character
In C code:
#include <stdio.h>
main()
{
int c, p;
p = EOF;
while ((c = getchar()) != EOF) {
if (c != ' ')
putchar(c);
if (c == ' ')
if (p != ' ')
putchar(' ');
p = c;
}
}
I am also starting out with the K&R textbook, and I came up with a solution that uses only the material which had been covered up until that point.
How it works:
First, set some counter 'blanks' to zero. This is used for counting blanks.
If a blank is found, increase the counter 'blanks' by one.
If a blank is not found, then first do a sub-test: is the counter 'blanks' equal or bigger than 1? If yes, then first, print a blank and after that, set the counter 'blanks' back to zero.
After this subtest is done, go back and putchar whatever character was not found to be a blank.
The idea is, before putcharing a non-blank character, first do a test to see, if some blank(s) were counted before. If there were blanks before, print a single blank first and then reset the counter of blanks. That way, the counter is zero again for the next round of blank(s). If the first character on the line is not a blank, the counter couldn't have increased, hence no blank is printed.
One warning, I haven't gone very far into the book, so I'm not familiar with the syntax yet, so it's possible that the {} braces might be written in different places, but my example is working fine.
#include <stdio.h>
/* Copy input to output, replacing each string of one or more blanks by a single blank. */
main()
{
int c, blanks;
blanks = 0;
while ((c = getchar()) != EOF) {
if (c != ' ') {
if (blanks >= 1)
printf(" ");
blanks = 0;
putchar(c); }
if (c == ' ')
++blanks;
}
}
Like many other people, I am studying this book as well and found this question very interesting.
I have come up with a piece of code that only uses what has been explained before the exercice (as I am not consulting any other resource but just playing with the code).
There is a while loop to parse the text and one if to compare the current character to the previous one.
Are there any edge cases where this code would not work ?
#include <stdio.h>
main() {
// c current character
// pc previous character
int c, pc;
while ((c = getchar()) != EOF) {
// A truthy evaluation implies 1
// (learned from chapter 1, exercice 6)
// Avoid writing a space when
// - the previous character is a space (+1)
// AND
// - the current character is a space (+1)
// All the other combinations return an int < 2
if ((pc == ' ') + (pc == c) < 2) {
putchar(c);
}
// update previous character
pc = c;
}
}
for(nb = 0; (c = getchar()) != EOF;)
{
if(c == ' ')
nb++;
if( nb == 0 || nb == 1 )
putchar(c);
if(c != ' ' && nb >1)
putchar(c);
if(c != ' ')
nb = 0;
}
Here is my answer, I am currently in the same spot you were years ago.
I used only the syntax taught until this point in the books and it reduces the multiple spaces into one space only as required.
#include<stdio.h>
int main(){
int c
int blanks = 0; // spaces counter
while ((c = getchar()) != EOF) {
if (c == ' ') { // if the character is a blank
while((c = getchar()) == ' ') { //check the next char and count blanks
blanks++;
// if(c == EOF){
// break;
// }
}
if (blanks >= 0) { // comparing to zero to accommodate the single space case,
// otherwise ut removed the single space between chars
putchar(' '); // print single space in all cases
}
}
putchar(c); //print the next char and repeat
}
return 0;
}
I removed the break part as it was not introduced yet in the book,hope this help new comers like me :)
This is a solution using only the techniques described so far in K&R's C. In addition to using a variable to achieve a finite state change for distinguishing the first blank space from successive blank spaces, I've also added a variable to count blank spaces along with a print statement to verify the total number. This helped me to wrap my head around getchar() and putchar() a little better - as well as the scope of the while loop within main().
// Exercise 1-9. Write a program to copy its input to its output, replacing
// each string of one or more blanks by a single blank.
#include <stdio.h>
int main(void)
{
int blank_state;
int c;
int blank_count;
printf("Replace one or more blanks with a single blank.\n");
printf("Use ctrl+d to insert an EOF after typing ENTER.\n\n");
blank_state = 0;
blank_count = 0;
while ( (c = getchar()) != EOF )
{
if (c == ' ')
{
++blank_count;
if (blank_state == 0)
{
blank_state = 1;
putchar(c);
}
}
if (c != ' ')
{
blank_state = 0;
putchar(c);
}
}
printf("Total number of blanks: %d\n", blank_count);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int c, flag=0;
while((c=getchar()) != EOF){
if(c == ' '){
if(flag == 0){
flag=1;
putchar(c);
}
}else{
flag=0;
putchar(c);
}
}
return 0;
}
I hope this will help.
/*a program that copies its input to its output, replacing each string of one or more blanks by a single blank*/
#include <stdio.h>
#include<stdlib.h>
int main(void)
{
double c;
char blank = ' ';
while((c = getchar()) != EOF)
{
if(c == ' ')
{
putchar(c);
while(( c = getchar() )== ' ')
{
if(c != ' ')
break;
}
}
if(c == '\t')
{
putchar(blank);
while((c = getchar()) == '\t')
{
if(c != '\t')
break;
}
}
putchar(c);
}
return 0;
}
// K & R Exercise 1.9
// hoping to do this with as few lines as possible
int c = 0, lastchar = 0;
c = getchar();
while (c != EOF) {
if (lastchar != ' ' || c != ' ') putchar(c);
lastchar=c;
c=getchar();
}
Considering what's asked in the question, I have also made sure that the program runs smooth in case of various tabs, spaces as well as when they're clubbed together to form various combinations!
Here's my code,
int c, flag = 1;
printf("Enter the character!\n");
while ((c = getchar()) != EOF) {
if (c == ' '||c == '\t') {
c=getchar();
while(c == ' '|| c == '\t')
{
c = getchar();
}
putchar(' ');
if (c == EOF) break;
}
putchar(c);
}
Feel free to run all test cases using various combinations of spaces and tabs.
Solution1: as per topics covered in the k&R book:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
if (c == ' ')
{while ( getchar() == ' ' )
; // ... we take no action
}
putchar(c);
}
return 0;
}
Solution2 : using program states:
int main()
{
int c, nblanks = 0 ;
while ((c = getchar()) != EOF)
{
if (c != ' ')
{ putchar(c);
nblanks = 0;}
else if (c==' ' && nblanks == 0) // change of state
{putchar(c);
nblanks++;}
}
return 0;
}
Solution3 : based on last seen char
int main()
{
int c, lastc = 0;
while ((c = getchar()) != EOF)
{
if ( c != ' ')
{putchar(c);}
if (c == ' ')
{
if (c==lastc)
;
else putchar(c);
}
lastc = c;
}
return 0;
}

Resources