Text stream K&R exercises


 
Thread Tools Search this Thread
Operating Systems OS X (Apple) Text stream K&R exercises
# 15  
Old 01-20-2010
Exercise 1-13, make a histogram. I would list my problems, but ohmygod...
# 16  
Old 01-25-2010
Okay, I've been working on 1-13.

Once I broke it down into tasks, perhaps it isn't that difficult.

I have, perhaps, broken it down further than I needed to, but doing so helped me wrap my mind around the process I want the computer to do.

Now what I have is a program that runs, accepts input, and then exits, without printing my bars, and without any clues to what's going wrong.

I have a function that prints the bars, and it works, as long as I hardcode input into it.

So I built a "Project" in Xcode, hoping to use the debugger to run the program and find the problems.

I am now researching how to use the debugger; I don't understand what it's telling me. I don't know what the registers are, I don't know how to track my variables while I type input into the running program, it's like sitting in a big, powerful diesel locomotive, and not knowing where the start button is. You know you're surrounded with options, but none of them are turned on.

So if any of you have suggestions about a tutorial or ultra-basic instructions for using the Debugger in Xcode, I would be very interested in reading it.

Thank you, yet again. Smilie
# 17  
Old 01-25-2010
Slow down, young grasshopper. At 1-13, you're still a long way from functions, and even more so from using an IDE!

You have to write a program to read in a bunch of words, and then print a histogram of the length of those words. So first you'll need one loop to read the input. Since you want a histogram of the length of the words, you don't need to save the words, only their length. To save that, you need an integer array, and for an proper histogram a counter of the total number of words. How do you discern between one word an another? Let's simplify this and declare a word to be a series of letters between 'A' and 'Z' or between 'a' and 'z'. Anything else is a separator between words.

For output, loop over the array of word lengths you have. Calculate the percentage they take on the total number of words, and for that size create an appropriately sized "bar" using another, nested, loop.

Remember, the K&R book was written at a time when C programming was done with command line utilities, and all exercises can be done using nothing but an editor, a C compiler, and a command line debugger (eg. gdb).
# 18  
Old 01-25-2010
Okay. Smilie

You know this stuff awfully well. You sound like you've been through it more than once. I don't remember textbooks I blew through ten years ago, let alone when K&R was written.

You wouldn't have taught it, would you? Smilie
# 19  
Old 01-25-2010
Nope, never taught it. Haven't even read it completely yet. I've picked up a second edition back in (what Americans would call) college when Pascal got boring and Assembler was yet out of reach. But you're almost spot on on the "10 years ago" part. And my above explanation isn't even specific to C, but I'd employ (pretty much) the same algorithm for any other language.

The most important thing I learned in my programming class: it doesn't matter what languages you know, but what algorithms, and whether or not you can apply them when needed. The above algorithm could probably be written in Perl in 2 lines (4, if you insist on strictures and warnings), but the algorithm would still be the same.
# 20  
Old 01-25-2010
Oh, dear.

I used more than two lines. I used more than two lines for the INTRODUCTION.

I re-wrote it this morning, with no functions.

Now it runs, but when you enter an EOF, it prints "Floating Point Exception", and no bars.

Here's the code I came up with.

(Warning, more than two lines. Smilie )

Code:
/*
 *  hist.c
 *  
 * Exercise 1-13. Write a program to print a histogram of the lengths of words in its input.
 * This version prints a horizontal histogram. It uses the character █ for the bars.
 * 
 */


#include <stdio.h>
#define	MAX_WORD_LENGTH	30	// The maximum number of letters in a word.
#define	NUMBER_WORDS 0	// To call the first member of the array.

int wordLength	[MAX_WORD_LENGTH]; // array to hold the counts; zero is the number of words

main() {
	
	int c; // counter
	int character; // the character we're looking at
	int p;	// printing counter
	int s;  // printing symbol
	
	for (c = 0; c <= MAX_WORD_LENGTH; c++) {
		wordLength[c] = 0;
	} // end initialization for loop
	
	c = 0; // set count to zero
	
	while ((character = getchar()) != EOF) { // get the character, stuff it into character, check for EOF
		
		
		if ((character >= 'a' && character <= 'z') || // if it's a lower case letter or
			character >= 'A' && character <= 'Z') {   // an upper case letter
			c++; //increment the counter
			
		} // end if
		
		else { // it's the end of the word, c holds the length of the word we just found.
			wordLength[c]++;
			wordLength[NUMBER_WORDS]++; // increment number of words
			c = 0; // re-set the counter for the next word
		} // end else
	} // end while loop
	
	/*******************
	 Printing- we've left the while loop because an EOF showed up
	 *******************/
	
	for (c = 1; c <= MAX_WORD_LENGTH; c++) {
		
		/* Note that this for loop starts with one, not zero.
		 This is because zero holds the number of words,
		 and each word had at least one letter. */
		
		/**************************************
		 This is a test printing sequence I used to make sure the right
		 members of the array were incrementing. I left it here in case
		 final protective fire full panic testing was needed.
		 
		printf("C-");
		printf("%d", c);
		printf(" is ");
		printf("%d \n", wordLength[c]);
		 **************************************/
		
		p = ((wordLength[c] / wordLength[MAX_WORD_LENGTH]) / 2); // Each symbol is 2%
		
		printf("%d", c);
		printf(" letters: ");
		
		for (s = 1; s <= p; s++) {
			printf("█");
		} // end printing for loop
		
		printf("\n");
		
	} // end for loop
} // end main

# 21  
Old 02-03-2010
Okay, here we go.

Life interfered, AGAIN, with my programming.

This is the basic program, now I'm looking at the problems with printing the histogram vertically.

More planning, obviously. Have to know in advance how high the highest bar will be, and how wide the graph will be.

Then I need to figure a way to lock the vertical bars into the correct horizontal column...

Anyway, here's the horizontal version.

I spent some time playing around with labels, but I couldn't get the "%" sign to print! Printf uses it for the signal, and it was really annoying.

Code:
/*
 *  hist.c
 *  
 * Exercise 1-13. Write a program to print a histogram of the lengths of words in its input.
 * This version prints a horizontal histogram. It uses the character █ for the bars.
 * 
 */


#include <stdio.h>
#define	MAX_WORD_LENGTH	30	// The maximum number of letters in a word.
#define	NUMBER_WORDS 0	// To call the first member of the array.

float wordLength	[MAX_WORD_LENGTH]; // array to hold the counts; zero is the number of words

main() {
	
	int c; // counter
	int character; // the character we're looking at
	float p;	// printing counter
	int s;  // printing symbol
	
	for (c = 0; c <= MAX_WORD_LENGTH; c++) {
		wordLength[c] = 0;
	} // end initialization for loop
	
	c = 0; // set count to zero
	
	while ((character = getchar()) != EOF) { // get the character, stuff it into character, check for EOF
		
		
		if ((character >= 'a' && character <= 'z') || // if it's a lower case letter or
			character >= 'A' && character <= 'Z') {   // an upper case letter
			c++; //increment the counter
			
		} // end if
		
		else { // it's the end of the word, c holds the length of the word we just found.
			wordLength[c]++;
			wordLength[NUMBER_WORDS]++; // increment number of words
			c = 0; // re-set the counter for the next word
		} // end else
	} // end while loop
	
	/*******************
	 Printing- we've left the while loop because an EOF showed up
	 *******************/
	
	for (c = 1; c <= MAX_WORD_LENGTH; c++) {
		
		/* Note that this for loop starts with one, not zero.
		 This is because zero holds the number of words,
		 and each word had at least one letter. */
		
		/**************************************
		 This is a test printing sequence I used to make sure the right
		 members of the array were incrementing. I left it here in case
		 final protective fire full panic testing was needed.
		printf("C-");
		printf("%d", c);
		printf(" is ");
		printf("%f \n", wordLength[c]);
		 **************************************/		 
		
		p = ((wordLength[c] / wordLength[NUMBER_WORDS]) * 100); // Each symbol is 1%
		
		printf("%2.0d", c);
		printf(" letters:");

		for (s = 1; s <= p; s++) {
					printf("█");
				} // end printing for loop
		
		printf("\n");
		
	} // end for loop
} // end main



---------- Post updated at 12:48 ---------- Previous update was at 12:44 ----------

Quote:
Originally Posted by pludi
The most important thing I learned in my programming class: it doesn't matter what languages you know, but what algorithms, and whether or not you can apply them when needed. The above algorithm could probably be written in Perl in 2 lines (4, if you insist on strictures and warnings), but the algorithm would still be the same.
Pludi, I've been thinking about this statement since I read it.

I'm starting to see what you mean, but I don't know.

Do you mean that knowing the principle of "For (x = 0, x<=y, x++)" is more important than knowing how to write it?

I think I see that. If you know what you want to do, then you only have to find out how to write it, rather than figuring out how to do it.

Or something. Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Help with a question in one of my exercises

Hello, so I'm taking unix in one of my classes and I've been having fun, but I got stuck at this one question that I'm supposed to know how to answer but I can't wrap my head around it, I figured I'll post it here and see if someone can shed some light into what I'm doing wrong. Here's the... (1 Reply)
Discussion started by: hiwolf25
1 Replies

2. Shell Programming and Scripting

Insert Text after one, two, three lines & so on..

I want to insert "Text" in each file as a place where I mentioned below "Insert Text Here". These files are something like news of newspaper. Generally, newspaper headlines contain one or two lines. I don't know how it can be identified whether Text is inserted after first line or second line. ... (10 Replies)
Discussion started by: imranrasheedamu
10 Replies

3. Shell Programming and Scripting

Extract & Manipulate continous data stream-- tcpdump

Hello; I have this rather tricky problem to solve --(to me, anyways) .. I am processing the following one liner with tcpdump.. tcpdump -i T3501 -A ether host 00:1e:49:29:fc:c9 or ether host 00:1b:2b:86:ec:1b or ether host 00:21:1c:98:a4:08 and net 149.83.6.0/24 | grep --line-buffered -B... (5 Replies)
Discussion started by: delphys
5 Replies

4. Shell Programming and Scripting

Array & text file

Hi all, i have a text file such as: 10 17:54:47,213 10 17:54:47,214 10 17:54:49,338 10 17:54:49,399 10 17:54:50,402 10 17:54:50,403 11 17:54:47,213 11 17:54:47,213 11 17:54:49,362 11 17:54:49,422 11 17:54:50,429 11 17:54:50,429 11 17:54:50,429 11 17:54:50,429 11 17:54:51,510 12... (10 Replies)
Discussion started by: sbamap
10 Replies

5. Shell Programming and Scripting

I would like to have some exercises to develop my skills

Hi , I would like to do some exercises/scripts in order to develop my skills in shell scripts, can someone pass me some links/suggestions where i can find this? Thanks a lot :) (3 Replies)
Discussion started by: prpkrk
3 Replies

6. Shell Programming and Scripting

[Video stream] network stream recording with mplayer

Hi I used this command: mplayer http://host/axis-cgi/mjpg/video.cgi -user root -passwd root \ -cache 1024 -fps 25.0 -nosound -vc ffh264 \ -demuxer 3 -dumpstream -dumpfile output.avi It's ok but... Video Playing is very fast! Why? Is it a synch problem? What parameter I have to use for... (1 Reply)
Discussion started by: takeo.kikuta
1 Replies

7. Shell Programming and Scripting

Need ideas for practice exercises in sh

I did an assignment for sh scripting back in november, and I found it quite fun learning. I would like to retain this knowledge as I'm pretty sure it was my only scripting assignment, from now on in my programming course we won't be doing any scripting apart from the typical makefile scripts. The... (6 Replies)
Discussion started by: gcampton
6 Replies

8. Shell Programming and Scripting

regex to remove text before&&after comma chars

Hi, all: I have a question about "cleaning up" a huge file with regular expression(s) and sed: The init file goes like this: block1,blah-blah-blah-blah,numseries1,numseries2,numseries3,numseries4 block2,blah-blah-blah-blah-blah,numseries,numseries2,numseries3,numseries4 ...... (3 Replies)
Discussion started by: yomaya
3 Replies

9. Shell Programming and Scripting

Shall Scripts exercises

I have just 3 things that I really need to know the solution, please allow me to show it. any help would be nice script that backup a file. The file name to backup should be provided as input parameter, the backup file should have the same file name with the extension ".bak". If the user... (1 Reply)
Discussion started by: anything
1 Replies

10. UNIX for Dummies Questions & Answers

exercises in shell

Hi, I am a beginner at shell scripting, though I have several years of Oracle programming experience. Can anyone recommend a site where I can find some exercises on shell programming. Is there anywhere I can telnet as I dont have UNIX OS on my PC? Thanks Rohit (1 Reply)
Discussion started by: rohitv
1 Replies
Login or Register to Ask a Question