PCEngineFans.com - The PC Engine and TurboGrafx-16 Community Forum

Non-NEC Console Related Discussion => Chit-Chat => Topic started by: Dark Fact on May 31, 2007, 06:46:04 PM

Title: The programming help thread!
Post by: Dark Fact on May 31, 2007, 06:46:04 PM
I've decided to start up this here thread in regards to programming, software design, the whole shibang.

Recently, I decided to dust off my old C programming textbook and get the old programming skills running again.  Now, for the record, I've completed my courses at my university and I'm getting my degree next week.  However, my programming skills have been dropping the past couple years and I want to get back on track when it comes time to get a good job in my programming profession.  That said, I've recently decided to go back to university for one more year to take a few extra credit courses in order to fulfill the requirements for a 4 year bachelors in Business Computing (the degree I'm getting next week is a 3 year bachelors in Business Computing).  Since I've already completed all my computing courses, all I can take is a couple of history and literature ones for the time being until I've got all my credits for a 4 year degree.  My goal is to have my programming skills sharpened by next spring so I can be ready to tackle the work force full time.

That said, I'm going to run into a few problems with my programs every now and then such as a function that just won't work for some reason, a stubborn loop, or incorrect data.  That's where I will ask you guys for advice.  If you can point out some things wrong in my programs, I would like to hear it.  Now, for the record, I don't expect anyone here to write the programs for me.  That is supposed to be my job and I need the experience.  All I'm saying is that if I come to a major snag that is beyond my comprehension, I would like a little help. :)

Finishing university is one thing, but getting a major job in my profession is a whole different ball game.  If I'm gonna go into the work force, I wanna go prepared.

So, with that said, let's get down to business.  I have a little program that I was working on in C today that is none other than the familiar "Fahrenheit to Celsius" conversion.  Now, for the record, the program works.  The problem I have with it is that I'm not sure if the output is correct.  The output seems correct but there was a stipulation in the textbook question saying that the celsius values need to be rounded to the nearest integer.  Oh, and by the way, the values have to be displayed as integers.  Here is the output:

CELSIUS     FAHRENHEIT
-----------------------
     -6             20
     -3             25
     -1             30
      1             35
      4             40
      7             45
     10            50
     12            55
     15            60
     18            65
     21            70
     23            75
     26            80
     29            85
     32            90
     35            95
     37           100

The Fahrenheit values are correct as the question asked me to record the values in five degree intervals.  It is the Celsius values that worry me.  For the hell of it, I converted my "int" values into "float" to test to see if they were more accurate and sure enough, they were.  It's just these integer values that leave me inconclusive.  This is why I need a second opinion on the matter.  Are these Celsius values accurate as an integer definition or are a few of the values not rounded properly?

I'm heading to bed now so I won't be back till tomorrow morning to check what you guys have said.  Any help is appreciated! Thanks. :)
Title: Re: The programming help thread!
Post by: Hobo Xiphas on May 31, 2007, 07:00:09 PM
You have to use float\double for the variables or else you will get incorrect values since the conversion uses division and it will truncate if you throw it into an int.

Use the truncf\trunc function to round off floats\doubles to the nearest integer respectively after you have done the conversion.

EDIT: I checked the libc man and the above won't work, you'll probably have to use an if structure with floor and ceil of some sort to get it working unless my horrible knowledge of C is making me forget a function in math.h.
Title: Re: The programming help thread!
Post by: Keranu on May 31, 2007, 07:12:16 PM
This thread is screaming nodtveidt.
Title: Re: The programming help thread!
Post by: offsidewing on June 01, 2007, 02:50:50 AM
Sheeee-it.  I got some programming knowledge for you.

Gorillas on Qbasic is the bomb.  Nibbler, not so much.

Oh how the Radioshack at the mall hated me C:\format bitches!!!

Gorillas ranks second on my coolest games ever made right behind Oregon Trail.
Title: Re: The programming help thread!
Post by: Kitsunexus on June 01, 2007, 03:17:40 AM
10 PRINT "ZACK ROX!"
GOTO 10
Title: Re: The programming help thread!
Post by: FM-77 on June 01, 2007, 04:58:11 AM
Sheeee-it.  I got some programming knowledge for you.

Gorillas on Qbasic is the bomb.  Nibbler, not so much.

Oh how the Radioshack at the mall hated me C:\format bitches!!!

Gorillas ranks second on my coolest games ever made right behind Oregon Trail.

Dude, Nibbler ROCKS!! Especially at speed 99. At least on a 25MHz 386. It was too ****ing fast on 486's.
Title: Re: The programming help thread!
Post by: offsidewing on June 01, 2007, 05:01:54 AM
Sheeee-it.  I got some programming knowledge for you.

Gorillas on Qbasic is the bomb.  Nibbler, not so much.

Oh how the Radioshack at the mall hated me C:\format bitches!!!

Gorillas ranks second on my coolest games ever made right behind Oregon Trail.

Dude, Nibbler ROCKS!! Especially when speed 99. At least on a 25MHz 386. It was too ****ing fast on 486's.

heck, we jumped from a 286 with upgraded 640K of RAM right to a blazing 486SX-33 with 4 whole megs of ram and a brusing 1 meg of video ram.  When I got into CAD (and Xwing), we got the clock tripler.
Title: Re: The programming help thread!
Post by: Dark Fact on June 01, 2007, 06:00:32 AM
Quote from: Xiphas
I checked the libc man and the above won't work, you'll probably have to use an if structure with floor and ceil of some sort to get it working unless my horrible knowledge of C is making me forget a function in math.h.
The requirement for the question was to have the entire output be in integers.  It also said to "round to the nearest integer".  This is a Chapter 6 question in my textbook that says I should only use the header <stdio.h>, a for loop, and integer values.  I'm not to use any if structures, ceil, floor or extra headers.  That output that you see in my first post is the best I got from it.  However, working out the values on a calculator, some celsius values don't appear properly rounded off like "-6", "-3", and "37".  When I put the values in float, the values are correct.  It's just in int that don't appear correct to me.  If this is the way C interprets the values in int, then there is nothing else I can do with my program.  However, if there is another way to make the values appear properly rounded in int, I would like to know.
Quote from: offsidewing
Sheeee-it.  I got some programming knowledge for you.

Gorillas on Qbasic is the bomb.  Nibbler, not so much.

Oh how the Radioshack at the mall hated me C:\format bitches!!!

Gorillas ranks second on my coolest games ever made right behind Oregon Trail.
Oh my God.  Those games bring back memories! I loved playing Gorillas in QBasic.  It was WORMS before WORMS! :D
Title: Re: The programming help thread!
Post by: akamichi on June 01, 2007, 06:33:59 AM
The requirement for the question was to have the entire output be in integers.  It also said to "round to the nearest integer".  This is a Chapter 6 question in my textbook that says I should only use the header <stdio.h>, a for loop, and integer values.  I'm not to use any if structures, ceil, floor or extra headers.  That output that you see in my first post is the best I got from it.  However, working out the values on a calculator, some celsius values don't appear properly rounded off like "-6", "-3", and "37".  When I put the values in float, the values are correct.  It's just in int that don't appear correct to me.  If this is the way C interprets the values in int, then there is nothing else I can do with my program.  However, if there is another way to make the values appear properly rounded in int, I would like to know.
If you're using ints to do the calculation, then you'll never be able to round the fractional part to the nearest integer because you'll only get whole numbers as a result.  In other words, integer division drops the remainder (truncate).  Now you could do the calculation using floats and then display the floats to make them look like ints.  But that has nothing to do with the calculation, it's just printing them to the screen in a particular format.

However, from what I understand from your initial post, if you're doing straight integer operations, what you have are the answers you should expect when using integer division.

Hope this helps.
Title: Re: The programming help thread!
Post by: Hobo Xiphas on June 01, 2007, 08:38:17 AM
It also said to "round to the nearest integer".

I can't see how you can get accurate results with the constraints the book gives you.  What you have now is the best you can do.
Title: Re: The programming help thread!
Post by: offsidewing on June 01, 2007, 08:42:35 AM
Oh my God.  Those games bring back memories! I loved playing Gorillas in QBasic.  It was WORMS before WORMS! :D

There's just something about lobbing bananas across a 14 inch radiation emitter.  Yeah, I played the hell out of it (with a buddy of course) until I found the coolness of Red Storm Rising.  It was only replaced by 688 Attack Sub.
Title: Re: The programming help thread!
Post by: Dark Fact on June 04, 2007, 04:17:22 PM
Anyone here know what the math formula is to calculate monthly sales projections? I need it in order to finish the last question on Chapter 6 of my programming textbook.  The whole program for that question is already done.  I just don't know what the monthly sales forecast formula is. ](*,)
Title: Re: The programming help thread!
Post by: offsidewing on June 04, 2007, 04:28:29 PM
Anyone here know what the math formula is to calculate monthly sales projections? I need it in order to finish the last question on Chapter 6 of my programming textbook.  The whole program for that question is already done.  I just don't know what the monthly sales forecast formula is. ](*,)

3.14r^2.  or is it y=mx+b?  oh, my favorite. MV=SPANK better know as f=m(dv/dt)=ma

Like my chinese Trig professer always used to say, "I like to see Pi."  Buddy, you and me both.

Title: Re: The programming help thread!
Post by: nat on June 04, 2007, 04:42:37 PM
Where the f*ck did this thread come from? It just appeared out of the blue right before my eyes with 11 new messages. Now I know what stevek666 is talking about. To be honest, I just thought he was mental.

This thread is screaming nodtveidt.

Really? I didn't hear anything.

Gorillas ranks second on my coolest games ever made right behind Oregon Trail.

I'll second you there (on the Oregon Trail deal). The Apple // version rules ALL. I still play it sometimes for old time's sake on my Apple //c+. Yes, I am being completely serious. The Macintosh version was OK, but too graphical and hunting wasn't as cool as in the Apple // version; you couldn't walk around the forest and shoot different directions.

Anyone here know what the math formula is to calculate monthly sales projections? I need it in order to finish the last question on Chapter 6 of my programming textbook.  The whole program for that question is already done.  I just don't know what the monthly sales forecast formula is. ](*,)

Yes, if it's as simple as what I think you're asking.

My entire job revolves around doing just that. That's right, I sit at a computer all day tabulating sales data and projecting sales and profit margins for the next week, month, and year. Then I devise new and illegal interesting ways to improve them. And in between when my boss isn't around I log on to www.pcenginefx.com/forums (http://www.pcenginefx.com/forums) and make fun of people.

(Sales MTD / Days of month that have passed) * number of days in month

For example, to project sales for June as of right now, and assuming my MTD sales are $50,000:

(50,000 / 3 (technically the 4th day isn't over so we won't count it) ) * 30 (30 days in June) = a projection of $500,000 for the month.
Title: Re: The programming help thread!
Post by: offsidewing on June 04, 2007, 04:49:09 PM

I'll second you there (on the Oregon Trail deal). The Apple // version rules ALL. I still play it sometimes for old time's sake on my Apple //c+. Yes, I am being completely serious. The Macintosh version was OK, but too graphical and hunting wasn't as cool as in the Apple // version; you couldn't walk around the forest and shoot different directions.


The MAC version of hunting licked balls.  Who the heck wants to shoot a 1 frame per minute shotgun from a fixed firing position.  Gimme a rifle, a wagon full of bullets, one color, and bring on the BEARS!

Around my office, I'm the boss.  Anyone caught posting on PCENGINEFX.COM during work hours (like I sometimes do) would immediately get a raise and promoted.  Sadly, no cool people work for me...
Title: Re: The programming help thread!
Post by: Necromancer on June 04, 2007, 05:14:58 PM
Where the f*ck did this thread come from? It just appeared out of the blue right before my eyes with 11 new messages. Now I know what stevek666 is talking about. To be honest, I just thought he was mental.

Great, now it's spreading.  Both nat and stevek666 are going nuckin' futs.

Around my office, I'm the boss.  Anyone caught posting on PCENGINEFX.COM during work hours (like I sometimes do) would immediately get a raise and promoted.  Sadly, no cool people work for me...

Are you hiring?  'Cause I'd be willing to relocate for some of this easy money.  :lol:
Title: Re: The programming help thread!
Post by: Dark Fact on June 04, 2007, 05:32:37 PM
Quote from: nat
Yes, if it's as simple as what I think you're asking.

My entire job revolves around doing just that. That's right, I sit at a computer all day tabulating sales data and projecting sales and profit margins for the next week, month, and year. Then I devise new and illegal interesting ways to improve them. And in between when my boss isn't around I log on to www.pcenginefx.com/forums (http://www.pcenginefx.com/forums) and make fun of people.

(Sales MTD / Days of month that have passed) * number of days in month

For example, to project sales for June as of right now, and assuming my MTD sales are $50,000:

(50,000 / 3 (technically the 4th day isn't over so we won't count it) ) * 30 (30 days in June) = a projection of $500,000 for the month.
The requirements for the question don't mention anything about specific days in a month.  The months are just given standard numbers from 1-6 since the question is for a six month projection.  Plus, there is the matter of growth rate percentages to deal with.  For instance, if the minimum assumed growth rate is 7%, then I need to post 6 month sales forecasts with the added growth rate percentage.  The growth rate goes up to a maximum of 4%.  So therefore, 7% would go to 11% or 5% would go to 9%.  I need a formula that disregards specific days in a month and takes into account growth rate percentages.
Title: Re: The programming help thread!
Post by: nat on June 04, 2007, 05:39:06 PM
The requirements for the question don't mention anything about specific days in a month.  The months are just given standard numbers from 1-6 since the question is for a six month projection.  Plus, there is the matter of growth rate percentages to deal with.  For instance, if the minimum assumed growth rate is 7%, then I need to post 6 month sales forecasts with the added growth rate percentage.  The growth rate goes up to a maximum of 4%.  So therefore, 7% would go to 11% or 5% would go to 9%.  I need a formula that disregards specific days in a month and takes into account growth rate percentages.

OK, well, that wasn't specified, but it changes everything. :) I knew it couldn't be as simple as that.

It would help me to see the actual text of the question, if it's not too much trouble...
Title: Re: The programming help thread!
Post by: Dark Fact on June 05, 2007, 08:02:49 AM
Sure, no problemo. :)

A paper products manufacturer needs a program to forecast its sales over a six-month period.  To do so requires knowing the value of the sales growth rate and how the sales grow over that period.  Write a program that asks the user to enter the minimum assumed growth rate (as a percent) and the sales for the current month.  Assume a linear growth, that is, the sales for a month equals a fixed percent (the growth rate) over the previous month.  The program should display, in a table, the projected sales for the minimum growth rate and for growth rates up to 4% greater than the minimum.  The table should look like the following, if the user enters 7 for the minimum growth rate and 30000 for the current month's sales.

Sales Projections
Current Month's Sales: 30000
Growth                                                                                   Month

Rate in %
1                2                3              4               5                6
7
8
9
10
11

NOTE: Month and growth are on the same line.  Stupid forum formatting or an optical illusion? :shock:
Title: Re: The programming help thread!
Post by: Hobo Xiphas on June 05, 2007, 02:40:46 PM
Use the code tag for preformatted stuff
Title: Re: The programming help thread!
Post by: offsidewing on June 05, 2007, 02:48:12 PM
Around my office, I'm the boss.  Anyone caught posting on PCENGINEFX.COM during work hours (like I sometimes do) would immediately get a raise and promoted.  Sadly, no cool people work for me...

Are you hiring?  'Cause I'd be willing to relocate for some of this easy money.  :lol:

Actually, yes.  Two positions that I always snicker after reading.

Rack Coordinator.  Yes, you manage racks.

Packaging Engineer.  Help design a better package.

Snicker, Snicker.

Better have all your shit done when I catch you on PCENGINEFX.COM. 
Title: Re: The programming help thread!
Post by: nat on June 05, 2007, 04:23:33 PM
A paper products manufacturer needs a program to forecast its sales over a six-month period.  To do so requires knowing the value of the sales growth rate and how the sales grow over that period.  Write a program that asks the user to enter the minimum assumed growth rate (as a percent) and the sales for the current month.  Assume a linear growth, that is, the sales for a month equals a fixed percent (the growth rate) over the previous month.  The program should display, in a table, the projected sales for the minimum growth rate and for growth rates up to 4% greater than the minimum.  The table should look like the following, if the user enters 7 for the minimum growth rate and 30000 for the current month's sales.


OK, now I understand what they're getting at.

However, I get the impression you are looking for a single complex formula that can be used to calculate everything in that table. Since I'm no math major, I'm not sure I can help you there without spending a lot of time pondering over it. :(

I know the way *I* would do it which might be the "long way" around:

month1projection = ((currentsales)rate1  + currentsales)
month2projection = ((month1projection)rate1 + month1projection)
...
month6projection = ((month5projection)rate1 + month5projection)

then for the next tier down:

month1projectiontier2 = ((currentsales)rate2 + currentsales)
etc

and that's assuming:

currentsales = Current month's sales
rate1...rate5 = minimum growth rate...minimum growth rate+.04

It would be fairly simple for me to write a program to do what the question asks using the simple formulas here but that seems like it's got to be too easy. Plus the program would be fairly bloated. I might be able to figure it out if I spent a lot of time on it, but math is not one of my strengths, sadly. That's why you'll never find me without a calculator within arm's reach.
Title: Re: The programming help thread!
Post by: Dark Fact on June 06, 2007, 07:53:53 AM
Math's not my best subject either so you're not alone. :wink:

This is part of the chapter that requires the use of for loops to write your programs. *hint* *hint*

EDIT: I took your formulas to task and made this part of the loop body:

Code: [Select]
for (month_count = MONTH_START; month_count <= MONTH_END; month_count++)
              {
                   projected_sales = (current_month_sales * (percent_count / PCT_CONVERSION) + current_month_sales);
                   current_month_sales = projected_sales;
                   printf("  %6.2lf", projected_sales);
              }
The program outputs the projected sales results in "projected_sales" and then assigns the results into "current_month_sales".  The output is displayed afterwards.  Then, when "month_count" increments, "projected_sales" will be given a new value based on the newly assigned values in "current_month_sales".  Does this work?
Title: Re: The programming help thread!
Post by: Kitsunexus on June 06, 2007, 08:01:56 AM
I'm so great at math I had to take remedial algebra and geometry and never got higher than C's.

This has no relevance to anything. Thank you. ;)
Title: Re: The programming help thread!
Post by: Necromancer on June 06, 2007, 08:29:11 AM
Better have all your shit done when I catch you on PCENGINEFX.COM. 

f*ck that noise!  I wanted to just roam pcenginefx.com all day and keep getting raises and promotions, but you'd actually expect me to work.  I'd only take the Packaging Engineer job if I could put my package in a giant cardboard box with an expanded polystyrene insert (damn, that sounds dirty too).
Title: Re: The programming help thread!
Post by: Kitsunexus on June 06, 2007, 09:41:19 AM
f*ck that noise!

Sound sex?  :-s  :? :-k
Title: Re: The programming help thread!
Post by: offsidewing on June 07, 2007, 10:35:38 AM
Better have all your shit done when I catch you on PCENGINEFX.COM. 

f*ck that noise!  I wanted to just roam pcenginefx.com all day and keep getting raises and promotions, but you'd actually expect me to work.  I'd only take the Packaging Engineer job if I could put my package in a giant cardboard box with an expanded polystyrene insert (damn, that sounds dirty too).

I'll tell you what.  I'll hire you as my admin, and you will be my PCENGINEFX.COM proxy poster.  Wait, no.  Cause then I'll have the ugliest admin in the building.  Hmmm...  I've got it.  I put you in logistics, but really, you'll spend your entire day keeping me apprised of all the posts in the forums.

"Hey, boss.  Nat just posted another thread saying that 'Spaceballs 3: The search for the second movie' makes for a better sequel than 'Big Trouble in Little Korea!'"
Title: Re: The programming help thread!
Post by: nat on June 07, 2007, 12:30:48 PM

"Hey, boss.  Nat just posted another thread saying that 'Spaceballs 3: The search for the second movie' makes for a better sequel than 'Big Trouble in Little Korea!'"


Well, it does.

Math's not my best subject either so you're not alone. :wink:

This is part of the chapter that requires the use of for loops to write your programs. *hint* *hint*

EDIT: I took your formulas to task and made this part of the loop body:

Code: [Select]
for (month_count = MONTH_START; month_count <= MONTH_END; month_count++)
              {
                   projected_sales = (current_month_sales * (percent_count / PCT_CONVERSION) + current_month_sales);
                   current_month_sales = projected_sales;
                   printf("  %6.2lf", projected_sales);
              }
The program outputs the projected sales results in "projected_sales" and then assigns the results into "current_month_sales".  The output is displayed afterwards.  Then, when "month_count" increments, "projected_sales" will be given a new value based on the newly assigned values in "current_month_sales".  Does this work?

Yeah, there you go. That works. What's next?
Title: Re: The programming help thread!
Post by: Dark Fact on June 07, 2007, 01:01:40 PM
That's what I thought.  Thanks for the help, nat.  I'll be sure to post here again when I need new help. :wink:

And Offsidewing, Kitsunexus, will you mind not spamming this thread? This is supposed to be a serious discussion thread from one fellow programmer to another.
Title: Re: The programming help thread!
Post by: Kitsunexus on June 07, 2007, 02:07:02 PM
13 posts are unrelated to the thread, in what was counted as a 29 post thread. That leaves us with 16 programming posts.


The law of the net says that in a thread hijack the predominant subject must be the one to continue on, so as you wish Dark Fact. I solemnly swear to leave this thread alone unless I have something related to programming to say.
Title: Re: The programming help thread!
Post by: offsidewing on June 07, 2007, 02:23:40 PM
I'm hosting a sales meeting on Tuesday.  I was going to get you some advice, but now I'm not gunna.

Nya nya-nya nya nya nyaaaaa.  Yes even successful business types post on PCENGINEFX.COM!!!!!!
Title: Re: The programming help thread!
Post by: Kitsunexus on June 07, 2007, 02:31:07 PM
I'm hosting a sales meeting on Tuesday.  I was going to get you some advice, but now I'm not gunna.

Nya nya-nya nya nya nyaaaaa.  Yes even successful business types post on PCENGINEFX.COM!!!!!!

What exactly do you do? In like 5 days I'll be a Customer Care Representative for T-Mobile specializing in pre-paid activation. ^__^

/Sorry, I broke my promise. :(
Title: Re: The programming help thread!
Post by: offsidewing on June 07, 2007, 02:45:56 PM
I'm pretty much a corporate locust, but in a good way.  Currently, I'm employed by a Supply Chain Conglomorant and I'm contracted to a major US automaker.  I'm a complex business practice problem solver.  If there's an underperforming operating group, they plug me in to make sense of it.  I don't hire and fire, I get people out of the "if it ain't broke.." and "it's not my job" mentality.  Before that I was an investment banker.  Before that an athlete type.  Before that I was a giant man-whore in college.  Before that I was one of two people in my huge high school to have a Turbo Grafx 16.

When I'm not dodging head hunters, I waste time on PCENGINEFX.COM instead of finishing a few written works.

Edit:  Oh, and I don't know a thing about forum posting etiquitte.  I thought this was spamming:

"Hey, I just broke up with my boyfriend and saw your profile.  I'm into 'rounder' guys, I wonder if you'd like to meet up for drinks sometime.  Email me at vixenchick@youthinkiamreal.com."
Title: Re: The programming help thread!
Post by: Dark Fact on June 07, 2007, 04:34:23 PM
Guys...seriously, no spamming.  I don't want to have to scroll through 3 or 4 posts about nothingness just to get to my answers from nat or someone else.  You're more than welcome to make up a new thread with all your silliness but let a guy have his spot, ok?
Title: Re: The programming help thread!
Post by: Kitsunexus on June 08, 2007, 06:32:47 AM
OMG USE THE PM SYSTEM GODDD U R SO ANNOYING AND I HAVE TOO MUCH SUGAR AND I THINK IM GONNA PUKE  :-#
Title: Re: The programming help thread!
Post by: Dark Fact on June 10, 2007, 04:05:42 AM
PM? This thread exists not only to help me out on programming problems but for anyone else who also wants similar programming help, hence why it's called "The programming help thread".  I don't need you to tell me how to ask for help, kthnx. 
Title: Re: The programming help thread!
Post by: Kitsunexus on June 10, 2007, 07:11:18 AM
That was a joke....


Anyway, I'm starting to learn Ruby (my first language to learn other than BASIC) so I'll probably use this threa dlegit from now on. ;)
Title: Re: The programming help thread!
Post by: Dark Fact on June 11, 2007, 02:05:02 PM
Thank you.  Now, back to business:

I've got a question that asks me to enter an integer, see if the integer is divisible by 6, and then display an appropriate message afterwards.  The coding was no problem.  The question on the other hand, is too generalized.  When it means "divisible by 6", does it mean getting a result that appears as a whole number and/or a real number?

Here's my code for the meat of the program:

Code: [Select]
for (int_count = EVEN; int_count <= int_prompt - int_prompt; int_count++)
        {
          if (int_prompt / DIVISIBILITY)
             printf("\nThe integer is divisible by 6.");
          else
             printf("\nThe integer is not divisible by 6.");
        }
DIVISIBILITY has been predefined as "6".  The result I get from the program has any number less than 6 be declared "not divisible" while any number equal to or greater than 6 declared "divisible".  Is this correct?

Title: Re: The programming help thread!
Post by: nat on June 11, 2007, 04:34:59 PM
I think I'd interpret the question to mean "Is the number evenly divisible by 6?"

I just can't see it any other way.

Assuming this, I don't think your program there does the job. If I understand you correctly, your code reports 1-5 as "not divisible" while 6 and up are "divisible". That's simply not correct if we're assuming what I'm assuming. 7 is not evenly divisible by 6. Neither is 8. Or 9.

Your program is simply checking the success of the (int_prompt / DIVISIBILITY) operation.

Let's change things around a little bit and use a modulus operator:

     if ( int_prompt % DIVISIBILITY == 0 )
          printf("\nHell yeah! We're cruisin' now!");
     else
          printf("\nYour number makes Nat a sad Panda.");


My C++ skills are a bit rusty but that looks right to me.
Title: Re: The programming help thread!
Post by: Dark Fact on June 11, 2007, 05:59:36 PM
Yeah, that did the trick. :) Modulus makes programs happy. :)
Title: Re: The programming help thread!
Post by: Dark Fact on June 19, 2007, 03:45:45 PM
New problem:

I have a program that requires me to check to see if the amount withdrawn from an account in regular cash withdrawals or checks exceeds the amount already present.  For instance, if I had $2000 in my account, deposited $1000, withdrew $3000 in cash, and another $3000 in checks, my closing balance would come to $-3000.

I have an if statement that checks to see if the closing balance falls below $0.00 and if it does, displays the amount that has exceeded.

However, for some strange reason, my program was able to display the amount a couple of times but afterwards, mysteriously stopped when I put a #define statement for "0.00".  Even when I tried to undo it, the statement still didn't appear.  Here's the code:

Code: [Select]
/* Prob 8-10
*  Created by Yuriy Mokriy
*/

#include <stdio.h>

#define ACCOUNT_LIMIT 0.00          /* The limit of the account between positive and negative balance */

main()
{
      int choice;                   /* The user's selected choice */
      float  opening_balance,       /* The opening account balance */
             total_deposit,         /* The total of all deposits */
             deposit,               /* The amount of the deposit */
             total_check,           /* The total of all checks */
             check,                 /* The amount of the check */
             total_withdrawal,      /* The total of all withdrawals */
             withdrawal,            /* The amount of the withdrawal */
             closing_balance;       /* The closing account balance */             
             
      /* Prompt the user for the opening balance */
     
      printf("Enter your opening account balance for the month: $");
      scanf("%f", &opening_balance);
     
      /* Display menu */
     
      printf("\n(D)Deposit");
      printf("\n(C)Check");
      printf("\n(W)Withdrawal");
      printf("\n(Q)Quit");
      printf("\nMake your selection: ");
      getchar();
      choice = getchar();
     
      /* Perform action based on choice */
     
      do 
      {
             if (choice == 'd' || choice == 'D')
             {
                  printf("\nEnter the amount of the deposit: $");
                  scanf("%f", &deposit);
                  total_deposit += deposit;
             }
             else if (choice == 'c' || choice == 'C')
             {
                  printf("\nEnter the amount of the check: $");
                  scanf("%f", &check);
                  total_check += check;
             }
             else if (choice == 'w' || choice == 'W')
             {
                  printf("\nEnter the amount of the withdrawal: $");
                  scanf("%f", &withdrawal);
                  total_withdrawal += withdrawal;
             }         
             else
                 printf("\nError.  You must select the following: ");
             
             printf("\n(D)Deposit");
             printf("\n(C)Check");
             printf("\n(W)Withdrawal");
             printf("\n(Q)Quit");
             printf("\nMake your selection: ");
             getchar();
             choice = getchar();
      } while (!(choice == 'q' || choice == 'Q'));
         
      /* Perform calculation */
     
      closing_balance = opening_balance + total_deposit - total_withdrawal - total_check;
     
      /* Check if account is overdrawn */
     
      if (closing_balance < ACCOUNT_LIMIT)
      {
         printf("\nWARNING: Your account has been overdrawn by $%.2f", closing_balance + ACCOUNT_LIMIT); 
         printf("\n");
      }
     
      /* Display totals */
     
      printf("\nOPENING BALANCE: $%.2f", opening_balance);
      printf("\nTOTAL DEPOSIT:   $%.2f", total_deposit);
      printf("\nTOTAL WITHDRAWAL:$%.2f", total_withdrawal);
      printf("\nTOTAL CHECKS:    $%.2f", total_check);
      printf("\n------------------------");
      printf("\nCLOSING BALANCE: $%.2f", closing_balance);
}
Can you figure out why the if statement that checks for the overdrawn amount in the account won't appear in my program? Because I'm just positively baffled here. :?

Another thing, the program instructions ask for me to display a warning at any time during the program a withdrawal or check results in a negative balance.  Does the program want me to check for an over withdrawal each time the check amount or cash withdrawal falls below $0.00 or does it have to be after the closing balance has been computed?

Take your time guys.  I think I said a mouthful. :P
Title: Re: The programming help thread!
Post by: nat on June 19, 2007, 06:28:31 PM
Is your tutorial a C or C++ tutorial? Not that it makes a whole lot of difference, but #DEFINE is relatively obsolete in C++. Even for C, your usage is not entirely correct.

#DEFINE is typically used to assign macros and boolean attributes to an identifier. It looks like you are thinking of #DEFINE as a way to assign a value to a variable, which it does not.

Forget #DEFINE. I try not to use #DEFINE at all unless absolutely necessary.

What your problem is here is that you are trying to compare a floating point (closing_balance) to an identifier. It's not going to printf that statement because that comparison will never be "true".

Delete the #DEFINE line and change your variable definitions to look as follows:

       float  opening_balance,       /* The opening account balance */
             total_deposit,         /* The total of all deposits */
             deposit,               /* The amount of the deposit */
             total_check,           /* The total of all checks */
             check,                 /* The amount of the check */
             total_withdrawal,      /* The total of all withdrawals */
             withdrawal,            /* The amount of the withdrawal */
             closing_balance,       /* The closing account balance */   
             nat_rules = 0.00;      /* Clearly, Nat is the man. */     
     


And of course, change all instances of "ACCOUNT_LIMIT" to "nat_rules".
Title: Well, I'm a dumbass!
Post by: Dark Fact on June 20, 2007, 07:59:37 AM
Okay, the problem with the overdrawn closing amount not appearing was a faux pas on my part.  I had another program earlier that used the same format but didn't need the overdrawn amount message to appear.  I just wound up  inadvertently running that previous program instead of the current one.

However, the question regarding where the overdrawn amount message needs to be displayed still stands.  Does it need to be displayed the moment the withdrawn or check amount goes below 0.00 or when the closing balance has been tabulated?
Title: Re: The programming help thread!
Post by: nat on June 20, 2007, 08:09:29 AM
I would say it needs to be displayed at the moment the balance goes negative, but that's a semantics issue.
Title: Re: The programming help thread!
Post by: Dark Fact on June 20, 2007, 03:16:24 PM
I thought as much.  I fixed the problem by creating a new variable called "account_balance" that assigns the opening balance to it as well as any deposits, withdrawals, or checks made.  I then cut and pasted the if statement that checks for overdrawn amounts into my while loop.  "account_balance" was used as a condition in the statement.  Finally, I assigned "account_balance" to "closing_balance" in order to display the closing balance amount in my program.

Thanks guys. :) I'll be back when I have another problem. :wink:
Title: Re: The programming help thread!
Post by: nat on June 20, 2007, 04:41:32 PM
Thanks guys. :) I'll be back when I have another problem. :wink:

Fine with me. But as far as I know, I'm only one person. My name isn't Legion. :)
Title: Re: The programming help thread!
Post by: offsidewing on June 25, 2007, 01:26:58 PM
Thanks guys. :) I'll be back when I have another problem. :wink:

Fine with me. But as far as I know, I'm only one person. My name isn't Legion. :)

So that means you are not many?

GIVE US A KISS, DEAR!!
Title: Re: The programming help thread!
Post by: nat on June 25, 2007, 01:30:23 PM
So that means you are not many?

GIVE US A KISS, DEAR!!

Be careful what you wish for.
Title: Re: The programming help thread!
Post by: Dark Fact on July 04, 2007, 01:45:38 PM
Okay, back with another problem.

I've been stewing with this program for a whole day.  The question in the book asks me to write a whole bunch of functions for an accounting program.  One of them involves getting the opening balance to an account, the other involves displaying a menu, another involves validating a user's choice, and another that displays the final results.

The problem I'm having with the program is the accumulation of the total amounts of deposits, withdrawals, and checks appearing properly.  Now, the funny thing is, when I'm typing in values for the program and finally end it afterwards, sometimes the values appear correct but other times, they don't.  For example, suppose I do the following:

Opening Balance: $40000
Deposit: $1000
Deposit: $1000
Withdrawal: $250
Withdrawal: $100
Check: $50

And then I end the program which gives me the following totals:

OPENING BALANCE: $40000
TOTAL DEPOSIT: $2000
TOTAL WITHDRAWAL: $350
TOTAL CHECKS: $50
--------------------------
CLOSING BALANCE: $41600

Now here's the same program using different amounts:

Opening Balance: $40000
Deposit: $60000
Deposit: $50000
Withdrawal: $24000
Check: $15000
Deposit: $25000

Here's what I may get:

OPENING BALANCE: $40000
TOTAL DEPOSIT: $-120000
TOTAL WITHDRAWAL: $156301606014
TOTAL CHECKS: $68500
--------------------------
CLOSING BALANCE: $1258917250218000000000000000000

See? Sometimes, good amounts, sometimes bad amounts.  Question is...what do I do to prevent any of these garbage values from appearing at all? Is it a problem with my identifiers? By the way, my identifiers for my variables are all double.
Title: Re: The programming help thread!
Post by: nat on July 04, 2007, 03:54:09 PM
First, if you're only dealing with whole dollars in this program change your data type for all your variables to long int, although it's probably not a big deal.

Next, without seeing your code, I'm going to guess you aren't initializing your variables. Depending how your program is set up this could make a big difference. I always believe it's good practice to initialize variables as you declare them regardless:

long int         nat_rules = 0,
                 dark_fact_rules = 0,
                 we_all_rule = 0;


Without seeing your code it's going to be tough debugging the program further.... Try the initialization thing and if that doesn't work, post up your code.
           
Title: Re: The programming help thread!
Post by: Dark Fact on July 05, 2007, 04:22:57 AM
I'm not using whole numbers in my program though.  I'm using real numbers.

I also initialized my totals for each category to 0.00 so that it has a value to start off with before accumulations.  However, this doesn't solve the problem as my program is still giving me crap values.

Here's the code to make it more easier:

Code: [Select]
/* Prob 10-3
*  Created by Yuriy Mokriy
*/

#include <stdio.h>
#include <stdlib.h>

double Get_Opening_Balance();                                 /* Gets the user's opening account balance */
void Choice_Menu();                                           /* Displays a menu for choices */
void Validate_Choice(double);                                 /* Validates the user's choice from the menu */
double Deposit(double, double);                               /* Gets the user's deposit amount */
double Withdrawal(double, double);                            /* Gets the user's withdrawal amount */
double Check(double, double);                                 /* Gets the user's check amount */
void Display_Results(double, double, double, double, double); /* Displays all results and totals */

main()
{   
      double open_balance_amount;            /* The user's opening account balance */
     
      /* Call functions */
     
      open_balance_amount = Get_Opening_Balance();
      Choice_Menu();     
      Validate_Choice(open_balance_amount);
}

double Get_Opening_Balance()
{
      double open_acct_balance;              /* The user's opening account balance */
     
      /* Prompt the user */
     
      printf("\nEnter the opening account balance: $");
      scanf("%lf", &open_acct_balance);
     
      if (open_acct_balance < 0.00)
         exit(0);
      else
         return open_acct_balance;     
}

void Choice_Menu()
{
      /* Display menu */
     
      printf("\nSelect your choice: ");
      printf("\n(D)Deposit");
      printf("\n(C)Check");
      printf("\n(W)Withdrawal");
      printf("\n(Q)Quit"); 
      printf("\n"); 
}

void Validate_Choice(double opening_balance_amt)
{
      char choice;                           /* The choice entered by the user */
      double total_deposit_amt,              /* The total amount deposited */
             total_withdrawal_amt,           /* The total amount withdrawn */
             deposited_amt,                  /* The amount deposited */
             withdrawn_amt,                  /* The amount withdrawn */
             total_check_amt,                /* The total check amount */
             check_amt,                      /* The check amount */
             account_balance,                /* The current account balance */
             closing_balance_amt;            /* The closing balance amount */
             
      /* Initialization */ 
       
      total_deposit_amt = 0.00;
      total_withdrawal_amt = 0.00;
      total_check_amt = 0.00;
      account_balance = 0.00;

      account_balance += opening_balance_amt;
         
      /* Get choice */
     
      getchar();
      choice = getchar();
     
      /* Validate choice */
     
      while (choice != 'q' || choice != 'Q')
      {
       if (choice == 'd' || choice == 'D')
       {
          account_balance = Deposit(deposited_amt, account_balance);
          total_deposit_amt = account_balance - opening_balance_amt - total_withdrawal_amt - total_check_amt;
       }
       else if (choice == 'w' || choice == 'W')
       {
          account_balance = Withdrawal(withdrawn_amt, account_balance);
          total_withdrawal_amt = -(account_balance - opening_balance_amt - total_deposit_amt - total_check_amt);
       }
       else if (choice == 'c' || choice == 'C')
       {
          account_balance = Check(check_amt, account_balance);
          total_check_amt = -(account_balance - opening_balance_amt - total_deposit_amt - total_withdrawal_amt);
       }
       else if (choice == 'q' || choice == 'Q')
       {
         closing_balance_amt = account_balance;
         Display_Results(opening_balance_amt, total_deposit_amt, total_withdrawal_amt, total_check_amt, closing_balance_amt);
         exit(0);
       } 
       else
         printf("\nError! You must enter the following choices listed on the menu.");
         
         Choice_Menu();
         getchar();
         choice = getchar();
      }       
}

double Deposit(double deposit_amount, double pres_account)
{         
      /* Prompt the user */
     
      printf("\nEnter the amount to be deposited: $");
      scanf("%lf", &deposit_amount);
     
      pres_account += deposit_amount; 
     
      return pres_account;
}

double Withdrawal(double withdrawal_amount, double present_account_balance)
{   
      /* Prompt the user */
     
      printf("\nEnter the amount to be withdrawn: $");
      scanf("%lf", &withdrawal_amount);
     
      if (withdrawal_amount > present_account_balance)
      {
        printf("\nWarning! The amount you have withdrawn exceeds your current account balance.\n");
        exit(1);
      }
     
      else
      {
        present_account_balance -= withdrawal_amount;
        return present_account_balance;
      }
}

double Check(double check_amount, double curr_account)
{       
      /* Prompt the user */
     
      printf("\nEnter the check amount $");
      scanf("%lf", &check_amount);
     
      if (check_amount > curr_account)
      {
        printf("\nWarning! The check amount exceeds your current account balance.\n");
        exit(1);
      }
     
      else
      {
        curr_account -= check_amount;
        return curr_account; 
      }
}

void Display_Results(double opening_balance, double total_deposit, double total_withdrawal, double total_check, double closing_balance)
{
      /* Display the results */
     
      printf("\nOPENING BALANCE:        $%.2lf", opening_balance);
      printf("\nTOTAL AMOUNT DEPOSITED: $%.2lf", total_deposit);   
      printf("\nTOTAL AMOUNT WITHDRAWN: $%.2lf", total_withdrawal);
      printf("\nTOTAL CHECK AMOUNT:     $%.2lf", total_check);
      printf("\n----------------------------------");
      printf("\nCLOSING BALANCE:        $%.2lf", closing_balance);
      printf("\n");
}
Title: Re: The programming help thread!
Post by: Dark Fact on July 07, 2007, 07:18:57 AM
So, any luck?
Title: Re: The programming help thread!
Post by: nat on July 07, 2007, 09:17:24 AM
Sorry, been busy with work so I haven't glanced at your code yet. I DO have a real job M-F. ;)

Today is Saturday so I'll take a look a little bit later and get back to you.
Title: Re: The programming help thread!
Post by: Dark Fact on July 07, 2007, 09:47:40 AM
Ok, no problemo. :)
Title: Re: The programming help thread!
Post by: Dark Fact on July 10, 2007, 04:50:11 PM
Hey nat, I've already found someone else to look at the problem for me.  The program is working fine now so you don't have to worry about it. :)
Title: Re: The programming help thread!
Post by: nat on July 10, 2007, 05:02:48 PM
sorry dude, I know I'm lame. I still haven't even looked at it yet. :) I'll get to it next time, I promise. But it always helps to post the code right away with your problem, cuz usually without code I can only speculate at what's going on.

What was the problem, BTW?
Title: Re: The programming help thread!
Post by: Bonknuts on July 11, 2007, 02:53:46 AM
First, if you're only dealing with whole dollars in this program change your data type for all your variables to long int, although it's probably not a big deal.

Next, without seeing your code, I'm going to guess you aren't initializing your variables. Depending how your program is set up this could make a big difference. I always believe it's good practice to initialize variables as you declare them regardless:

long int         nat_rules = 0,
                 dark_fact_rules = 0,
                 we_all_rule = 0;


Without seeing your code it's going to be tough debugging the program further.... Try the initialization thing and if that doesn't work, post up your code.

Funny, I've heard the argument for not initializing your variables on declaration - for debugging reasons.

Title: Re: The programming help thread!
Post by: nat on July 11, 2007, 03:36:47 AM

Funny, I've heard the argument for not initializing your variables on declaration - for debugging reasons.

Well, you're probably a much more serious/experienced programmer than I am.

I'm sure there are merits to both "philosophies" but in my experience I've found it beneficial to initialize variables on declaration more often than not. As with everything, there are exceptions to the rule....
Title: Re: The programming help thread!
Post by: Bonknuts on July 11, 2007, 05:52:49 PM

Quote
I'm sure there are merits to both "philosophies" but in my experience I've found it beneficial to initialize variables on declaration more often than not. As with everything, there are exceptions to the rule....

 I totally agree. I had an associate once tell me there only one way to do things - insinuating that there is only one right way. I nodded my head, but laughed to myself. I lost *all* respect for him after that  :mrgreen:

 I always initialized my variables in declaration in the past. I just came across that article recently.

 I'm still "amateur hour" in C - ASM's my strong point.



Title: Re: The programming help thread!
Post by: guyjin on July 12, 2007, 02:17:42 AM

 I totally agree. I had an associate once tell me there only one way to do things - insinuating that there is only one right way.


Yeah, pretty much anyone who says this, or anything like it, is a tool and can safely be ignored.*

*(unless you're dealing with potentially fatal stuff, then it's okay sometimes)
Title: Re: The programming help thread!
Post by: Dark Fact on July 23, 2007, 07:46:54 AM
Quote from: nat
sorry dude, I know I'm lame. I still haven't even looked at it yet. Smile I'll get to it next time, I promise. But it always helps to post the code right away with your problem, cuz usually without code I can only speculate at what's going on.

What was the problem, BTW?
Sorry for the late reply.  The problem I had involved finding a way to add up total deposits, withdrawals, and checks within my functions and then returning those totaled values to the Validate_Choice function.  However, the problem always put out incorrect values.  After re-reading the question, I found out that I wasn't supposed to total up my deposits, withdrawals, and checks within their own functions, but within Validate_Choice. 

Anyways, a friend of mine over MSN messenger was able to point out that problem to me and lo and behold, my problem is fixed.

Nat, chances are I'll be asking for help from my other friend over MSN when it comes to programming in the future.  No offense, but I can't really wait a week or two for you to look at my program and tell me what's wrong.  I need solutions, stat.

If I run into additional problems where I need to ask for further help, I'll let you know. :wink:
Title: Re: The programming help thread!
Post by: nat on July 23, 2007, 03:51:33 PM
Quote from: nat
sorry dude, I know I'm lame. I still haven't even looked at it yet. Smile I'll get to it next time, I promise. But it always helps to post the code right away with your problem, cuz usually without code I can only speculate at what's going on.

What was the problem, BTW?

Nat, chances are I'll be asking for help from my other friend over MSN when it comes to programming in the future.  No offense, but I can't really wait a week or two for you to look at my program and tell me what's wrong.  I need solutions, stat.

If I run into additional problems where I need to ask for further help, I'll let you know. :wink:

 :oops: Sorry... Again.

Is this for some kind of class, or something?

Anyway, yeah, I'm always here to help if you need/want it. I don't usually take that long to respond. Really.
Title: Re: The programming help thread!
Post by: Dark Fact on July 25, 2007, 12:34:40 PM
No, it wasn't in a class.  It's just your typical C function. :wink:

I'll let you know in the future again if I have trouble. :wink:
Title: Re: The programming help thread!
Post by: Dark Fact on July 25, 2007, 02:00:10 PM
Okay, I've got another thing here with my program that I need a third opinion on.  It's a program that requires me to read in values using an array and then after all the values have been entered, display the minimum value, maximum value, median, and average.

Although the program works, I'm not too sure about the minimum value procedure.  I had a bug with my program that involved displaying "0.00" for minimum value every time the program finishes.  For instance, I would type in values from 1.00 to 20.00 and then the program would display the values in descending order.  The maximum value is 20.00 while the minimum value is 1.00.  The program always displays 0.00 as minimum value.

I corrected the problem by initializing minimum_income to 1.00.  While it corrected the problem, I'm wondering if this kind of procedure is acceptable? Take a look at the code and tell me what you think:

Code: [Select]
/* Prob 11-5
*  Created by Yuriy Mokriy
*/

#include <stdio.h>

#define HOMES 20                        /* The maximum number of homes surveyed */

main()
{
      float household_incomes[HOMES],   /* The array to store the incomes */   
            maximum_income,             /* The maximum income amount in the survey */
            minimum_income,             /* The minimum income amount in the survey */
            average_income,             /* The average income amount in the survey */
            total_income,               /* The total income amount from the survey */
            median_income;              /* The median income amount in the survey */
      int income_count,                 /* Counts the incomes in the survey */
          limit,                        /* Keeps track of how far to go on a pass */
          pass,                         /* The number of the pass */
          temp;                         /* Temporarily stores income amounts for sorting */
     
      /* Initialization */
     
      total_income = 0.00;
      average_income = 0.00;
      median_income = 0.00;
      maximum_income = 0.00;
      minimum_income = 1.00;
     
      /* Prompt for incomes */
     
      for (income_count = 0; income_count < HOMES; income_count++)
      {
       printf("\nEnter the income amount for home #%d: $", income_count + 1);
       scanf("%f", &household_incomes[income_count]);
       total_income += income_count + 1;
       
       /* Determine maximum income */
       
       if (household_incomes[income_count] > maximum_income)
        maximum_income = household_incomes[income_count];
       
       /* Determine minimum income */
       
       if (household_incomes[income_count] < minimum_income)
        minimum_income = household_incomes[income_count];
      }
       
      /* Calculate median and average income */
     
      average_income = total_income / HOMES;
      median_income = ((household_incomes[10] - 1) + (household_incomes[11] - 1)) / 2;

      /* Sort the array in descending order */
     
      limit = HOMES - 2;
     
      for (pass = 1; pass <= HOMES - 1; pass++)
      {
       for (income_count = 0; income_count <= limit; income_count++)
        if (household_incomes[income_count] < household_incomes[income_count + 1])
        {
         temp = household_incomes[income_count];
         household_incomes[income_count] = household_incomes[income_count + 1];
         household_incomes[income_count + 1] = temp;
        }
        --limit;
      }
     
      /* Display the sorted incomes */
     
      printf("\nThe incomes in decreasing order are as follows:\n");
     
      for (income_count = 0; income_count < HOMES; income_count++)
       printf("$%.2f ", household_incomes[income_count]);
      printf("\n");
       
      /* Display the results */
     
      printf("\nMAXIMUM INCOME: $%.2f", maximum_income);
      printf("\nMINIMUM INCOME: $%.2f", minimum_income);
      printf("\nAVERAGE INCOME: $%.2f", average_income);
      printf("\nMEDIAN INCOME:  $%.2f", median_income);   
      printf("\n");
}

Is it okay to use 1.00 as minimum income or do I need to have it set to 0.00 and find another way to fix the problem?
Title: Re: The programming help thread!
Post by: nat on July 25, 2007, 04:27:05 PM
Hmm..

If I understand the spirit of your problem correctly, I don't think your solution is correct.

The reason the program always displayed "0" for minimum income before you initialized it to "1" is because using your code:

   if (household_incomes[income_count] < minimum_income)
        minimum_income = household_incomes[income_count];


...that condition was never true unless you entered a negative income. So minimum_income was never set and retained a value of "0". Follow me?

I think a proper solution would be to initialize "minimum_income" on the first loop through with whatever you happen to enter as an income rather than initializing it before the loop. For example inserting the code:

   if (income_count == 0)
        minimum_income = household_incomes[income_count];


...right before the if statement that checks to see if the current income is lower than the current minimum should initialize the minimum_income variable on the first loop through.

Make sense?
Title: Re: The programming help thread!
Post by: Dark Fact on July 26, 2007, 06:38:57 AM
I just gave that a shot.  It works great now. :)

My friend over MSN suggested that I use the initialization method for maximum_income and minimum_income but I felt that this just didn't sit right with me as the program required me to determine maximum and minimum income based on inputted values, not on comparisons with pre-initialized values.

Anyways, thanks for the help.  Arrays have been kicking my ass lately.
Title: Re: The programming help thread!
Post by: Dark Fact on August 16, 2007, 11:12:25 AM
Got another problem.

I have a program that requires me enter text at the terminal.  After I'm finished entering text, I'm then required to provide totals of each letter instance in the text.  For example, if I have a piece of text saying hahayoulose, the program would have to count up these total letters:

total 'a' = 2
total 'e' = 1
total 'h' = 2
total 'l' = 1
total 'o' = 2
total 's' = 1
total 'u' = 1
total 'y' = 1

All other letters would be read in as 0.  I require an array of counters for each letter in order to add up the values.  The program should not distinguish between uppercase and lowercase.  So, if I type in 'a' or 'A', it would still be added to my variable called 'a_count'.  The program also requires an EOF (end-of-file) character to terminate input.

Here's what I have for my code so far:

Code: [Select]
/* Prob 11-9
*  Created by Yuriy Mokriy
*/

#include <stdio.h>

#define ALPHABET_TOTAL 25                 /* The total number of letters in the alphabet */

main()
{
      char text[ALPHABET_TOTAL],          /* Text inputted by the user */
           letter_count;                  /* array subscript for text */
          /* The following declarations below are the array subscripts for the 'text' variable */
      int a_count = 0,
          b_count = 0,
          c_count = 0,
          d_count = 0,
          e_count = 0,
          f_count = 0,
          g_count = 0,
          h_count = 0,
          i_count = 0,
          j_count = 0,
          k_count = 0,
          l_count = 0,
          m_count = 0,
          n_count = 0,
          o_count = 0,
          p_count = 0,
          q_count = 0,
          r_count = 0,
          s_count = 0,
          t_count = 0,
          u_count = 0,
          v_count = 0,
          w_count = 0,
          x_count = 0,
          y_count = 0,
          z_count = 0;
         
      /* Text input */
     
      printf("\nPlease enter text.  Terminate program by pressing enter: ");
      text[letter_count] = getchar();
     
     while (text[letter_count] = getchar() != EOF)
      {
       for (letter_count = 'a'; letter_count <= 'z'; letter_count++)
       {
        while (text[letter_count] = getchar() != '\n')
        {
          if (text[letter_count] == 'a')
           ++a_count;
          if (text[letter_count] == 'b')
           ++b_count;
          if (text[letter_count] == 'c')
           ++c_count;
          if (text[letter_count] == 'd')
           ++d_count;
          if (text[letter_count] == 'e')
           ++e_count;
          if (text[letter_count] == 'f')
           ++f_count;
          if (text[letter_count] == 'g')
           ++g_count;
          if (text[letter_count] == 'h')
           ++h_count;
          if (text[letter_count] == 'i')
           ++i_count;
          if (text[letter_count] == 'j')
           ++j_count;
          if (text[letter_count] == 'k')
           ++k_count;
          if (text[letter_count] == 'l')
           ++l_count;
          if (text[letter_count] == 'm')
           ++m_count;
          if (text[letter_count] == 'n')
           ++n_count;
          if (text[letter_count] == 'o')
           ++o_count;
          if (text[letter_count] == 'p')
           ++p_count;
          if (text[letter_count] == 'q')
           ++q_count;
          if (text[letter_count] == 'r')
           ++r_count;
          if (text[letter_count] == 's')
           ++s_count;
          if (text[letter_count] == 't')
           ++t_count;
          if (text[letter_count] == 'u')
           ++u_count;
          if (text[letter_count] == 'v')
           ++v_count;
          if (text[letter_count] == 'w')
           ++w_count;
          if (text[letter_count] == 'x')
           ++x_count;
          if (text[letter_count] == 'y')
           ++y_count;
          if (text[letter_count] == 'z')
           ++z_count;
        }
       }
         
       for (letter_count = 'A'; letter_count <= 'Z'; letter_count++)
       {
        while (text[letter_count] = getchar() != '\n')
        {
          if (text[letter_count] == 'A')
           ++a_count;
          if (text[letter_count] == 'B')
           ++b_count;
          if (text[letter_count] == 'C')
           ++c_count;
          if (text[letter_count] == 'D')
           ++d_count;
          if (text[letter_count] == 'E')
           ++e_count;
          if (text[letter_count] == 'F')
           ++f_count;
          if (text[letter_count] == 'G')
           ++g_count;
          if (text[letter_count] == 'H')
           ++h_count;
          if (text[letter_count] == 'I')
           ++i_count;
          if (text[letter_count] == 'J')
           ++j_count;
          if (text[letter_count] == 'K')
           ++k_count;
          if (text[letter_count] == 'L')
           ++l_count;
          if (text[letter_count] == 'M')
           ++m_count;
          if (text[letter_count] == 'N')
           ++n_count;
          if (text[letter_count] == 'O')
           ++o_count;
          if (text[letter_count] == 'P')
           ++p_count;
          if (text[letter_count] == 'Q')
           ++q_count;
          if (text[letter_count] == 'R')
           ++r_count;
          if (text[letter_count] == 'S')
           ++s_count;
          if (text[letter_count] == 'T')
           ++t_count;
          if (text[letter_count] == 'U')
           ++u_count;
          if (text[letter_count] == 'V')
           ++v_count;
          if (text[letter_count] == 'W')
           ++w_count;
          if (text[letter_count] == 'X')
           ++x_count;
          if (text[letter_count] == 'Y')
           ++y_count;
          if (text[letter_count] == 'Z')
           ++z_count;
        }
       }
      }         
      printf("\ntotal a or A: %d", a_count);
      printf("\ntotal b or B: %d", b_count);
      printf("\ntotal c or C: %d", c_count);
      printf("\ntotal d or D: %d", d_count);
      printf("\ntotal e or E: %d", e_count);
      printf("\ntotal f or F: %d", f_count);
      printf("\ntotal g or G: %d", g_count);
      printf("\ntotal h or H: %d", h_count);
      printf("\ntotal i or I: %d", i_count);
      printf("\ntotal j or J: %d", j_count);
      printf("\ntotal k or K: %d", k_count);
      printf("\ntotal l or L: %d", l_count); 
      printf("\ntotal m or M: %d", m_count);
      printf("\ntotal n or N: %d", n_count);
      printf("\ntotal o or O: %d", o_count);
      printf("\ntotal p or P: %d", p_count);
      printf("\ntotal q or Q: %d", q_count);
      printf("\ntotal r or R: %d", r_count);
      printf("\ntotal s or S: %d", s_count);
      printf("\ntotal t or T: %d", t_count);
      printf("\ntotal u or U: %d", u_count);
      printf("\ntotal v or V: %d", v_count);
      printf("\ntotal w or W: %d", w_count);
      printf("\ntotal x or X: %d", x_count);
      printf("\ntotal y or Y: %d", y_count);
      printf("\ntotal z or Z: %d", z_count);
}

The array itself has a capacity of 25 to fit 25 letters of the alphabet.  The problem with the program that I keep having is that it just keeps hanging on me after I finished my input.  I suspect it to be a problem with my EOF, but I 'm not sure how to fix this.  I have a couple of for loops that count the presence of each letter both in lowercase and uppercase with the appropriate accumulator being incremented for each instance found.  If anyone can figure out what's wrong, it would be greatly appreciated. :)
Title: Re: The programming help thread!
Post by: Bonknuts on August 16, 2007, 01:12:38 PM
Just wanted to point out something - there's no need to write that many if statements for the whole alphabet, let alone two sets for upper and lowercase.

In ASCII you can avoid case sensitive checking, if case is not important. Bit 5 of the byte is set when the character is upper case and clear when the character is lower case.

Code: [Select]
unsigned char get_char;
unsigned int count_array[25]; 

   //note: I usually make my arrays a little bigger then the space I need incase I overwrite another area of memory with an out of bounds pointer
.
.
.
  get_char|=0x60;
That will convert all alphabetical characters to lower case. Use get_char&=0x5F to convert it to upper case.

 You'd probably want to check to see of the input char is within the correct range first:

Code: [Select]


 if( (get_char>0x40 && get_char<0x5b) || (get_char>0x60 && get_char<0x7b) )
  {
      get_char&=0x5F;   //convert to lowercase
      get_char-=0x41;   //subtract offset to beginning char starts at 0
      count_array[get_char]++;   //use the char as an index into your array and increment that specific usage
  } else {
            //error
         }


Title: Re: The programming help thread!
Post by: Dark Fact on August 16, 2007, 04:39:21 PM
The chapter examples in my textbook doesn't use specific hexadecimal notation in retrieving character values.  A previous example made use of a for loop to count each letter specifically and increment the accumulators if an instance is found.

The example that you provided may read in the values but what am I supposed to do for output? My question asks to display the number of each letter instance in the inputted text.
Title: Re: The programming help thread!
Post by: Bonknuts on August 16, 2007, 05:38:32 PM
hmm.. how about this:

Code: [Select]
  for(int i=0,i<25,i++)
  {
     printf("\n total %s or %s: %d", (i + 0x41), (i + 0x61), count_array[i]);
  }
Title: Re: The programming help thread!
Post by: nat on August 17, 2007, 04:24:25 AM
Looks like Bonknuts beat me to this one.
Title: Re: The programming help thread!
Post by: Dark Fact on August 17, 2007, 08:16:32 AM
My program crashed. :(
Title: Re: The programming help thread!
Post by: nat on August 17, 2007, 09:18:51 AM
Still not working for you?

I'll look at it as soon as I'm off work.
Title: Re: The programming help thread!
Post by: Bonknuts on August 18, 2007, 06:14:38 AM

 What compiler are you using? Knowing your way around the debugger is very import (I'd say a must). You can easily(usually) find out at what point the program is crashing when stepping through the debugger.

 Also another way to debug your could is with process of elimination. Like for instance, cut the program down to:
Code: [Select]
     while (text[letter_count] = getchar() != EOF)
      {
          letter_count++;
      }

 hint: I'd take a look at that test statement.
Title: Re: The programming help thread!
Post by: Dark Fact on August 19, 2007, 04:33:48 PM
I've tried modifying the code like this but the program still leaves me hanging:

Code: [Select]
/* Prob 11-9
*  Created by Yuriy Mokriy
*/

#include <stdio.h>
#include <stdlib.h>

#define ALPHABET_TOTAL 25                 /* The total number of letters in the alphabet */

main()
{
      unsigned int text[ALPHABET_TOTAL];  /* Array to store all letter instances of the alphabet */
      int letter_count,                   /* Counts the letter instances in the text input */
          char_count = 0;                 /* Counts the letters in the text input */
     
       
      /* Text input */
     
      printf("\nPlease enter text.  Terminate program by pressing enter: ");
      text[char_count] = getchar();

      while (text[char_count] = getchar() != EOF)
      {
       if (text[char_count] = getchar() == EOF)
        break;
       else
       {
        ++char_count;
        while (text[char_count] = getchar() != '\n')
        {
         if (text[char_count] = getchar() == '\n')
          break;
         else
          ++char_count;
        }
       }
      }
     
      for (letter_count = 0; letter_count < ALPHABET_TOTAL; letter_count++)
      {                 
       printf("\n total %c or %c: %d", (char_count + 0x41), (char_count + 0x61), text[char_count]);
     
       if((getchar() > 0x40 && getchar() < 0x5b) || (getchar() > 0x60 && getchar() < 0x7b))
       {
        text[char_count] &= 0x5F;
        text[char_count] -= 0x41;
        text[char_count]++;
       }
       else
       {
        printf("\nError.");
        exit(1);
       }
      }     
       
     
}
The program is really stubborn with that EOF statement.  I've tried inserting a couple of break statements to break the loop but that hasn't worked.  I also tried using a different character count variable.  What am I doing wrong now? :(
Title: Re: The programming help thread!
Post by: Bonknuts on August 20, 2007, 01:12:24 PM
 I'd look at that test statement inside of the while loop. Looks like you already call getchar() once, why call it again?

 Actually I think you want use getche() instead of getchar() for the test loop, though I don't think EOF will work in that case. Getchar() will grab multiple characters from a buffer and release when enter is pressed, getche() will grab a single character at a time. Look up the ascii key code for "enter" and poll that instead, for using getche().
Title: Re: The programming help thread!
Post by: Dark Fact on September 02, 2007, 02:33:00 PM
Okay, this is the most simplified format of the program I've made thus far. 

Code: [Select]
/* Prob 11-9
*  Created by Yuriy Mokriy
*/

#include <stdio.h>
#include <stdlib.h>

#define ALPHABET_TOTAL 25                    /* The total number of letters in the alphabet */

main()
{
      int  text[ALPHABET_TOTAL] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
           alpha_count,                      /* Counts the letters in the alphabet */
           char_count = 0,                   /* Counts the instances of each letter */
           letter_count = 0;                 /* Counts the letters in the text input */
      char text_input;                       /* The text inputted by the user */
     
      /* Text input */
     
      printf("\nPlease enter text.  Terminate program by pressing Ctrl+Z: ");
      text_input = getchar();
     
      /* Increment counter if not End Of File */
     
      while (text_input = getchar() != EOF)
       ++letter_count;
   
      /* Display the results */
   
      for (alpha_count = 65; alpha_count <= 90; alpha_count++)
      {
       if (getchar() == text[alpha_count] || getchar() == text[alpha_count + 32])
        char_count++;
       printf("\nTotal %c or %c: %d", alpha_count, alpha_count + 32, char_count);
      }
}
I haven't used getche() because my textbook doesn't cover that and I haven't seen anything good come out of that when I tried it in my program.  I declared a couple of variables called "alpha_count" to count all the letters in the alphabet and "char_count" to increment the letter instances in my block of text.

Now here's the kicker.  Upon reading the question more thoroughly, the author's definition of the "end-of-file" character is the usage of Ctrl+Z to break out of the loop and display the results.  That solves one problem. :)  However, the program is not counting the letter instances.

Here's the original question if you want to know what the author is getting at:

Write a program that prompts the user to enter text at the terminal.  When the user finishes entering text, he or she should enter the appropriate end-of-file character to terminate input.  The program should count the frequency of each letter of the alphabet.  The program should not distinguish an uppercase letter from a lowercase letter.  When the user finishes inputting text, the program should display each letter and its output.

Here's the hint given by the author:

Declare an array of counters, one for each letter.  Use the letter itself as the subscript that determines which array element to increment.  To do this, the program must convert the letter to the corresponding subscript.  Remember that the decimal ASCII values of the lowercase letters are 97 to 122 and the uppercase letters are 65 to 90.

So basically, the only problem left with the program is to count the letter instances of the text.  Everything else works fine.
Title: Re: The programming help thread!
Post by: Dark Fact on September 13, 2007, 05:06:06 AM
Well, after a couple of mind numbing weeks, I believe I finally got this sumbitch figured out:

Code: [Select]
/* Prob 11-9
*  Created by Yuriy Mokriy
*/

#include <stdio.h>

#define ALPHABET_TOTAL 26                    /* The total number of letters in the alphabet */

main()
{
      int text[ALPHABET_TOTAL] = {0},        /* Array sized 26, acting as counters for all characters 'a' .. 'z'  (case insensitive) */     
          text_input,                        /* Reads in the text input as characters */
          ASCII_count,                       /* The ASCII numerical representation of letters in the alphabet */
          alpha;                             /* boolean "flag" which turns to 0 (false) in case of a non-alpha character */
     
      /* Initialization */
     
      text_input = 0;
      ASCII_count = 0;
      alpha = 0;

      /* Get input */
     
      printf("\nPlease enter text.  Terminate program using Ctrl+Z: ");
     
      while( text_input != EOF )
      {
        alpha = 1;
        text_input = getchar();   
       
      /* If input is alphabetical, convert to a number 0-25 so that it can be used as an array index locator */
     
      if(text_input >= 'a' && text_input <= 'z')
       text_input -= 'a';
      else if(text_input >= 'A' && text_input <= 'Z')
       text_input -= 'A';

      /* Non-alphabetical character, set the alpha flag to false */
   
      else
       alpha = 0;

      /* Increment the appropriate counter in the text array as long as the character is alphabetical */
   
      if(alpha)
       text[text_input]++;
     }
     
     /* Display results */
     
    for (ASCII_count; ASCII_count <= 25; ASCII_count++)
     printf("\nTotal %c or %c: %d", ASCII_count + 'a', ASCII_count + 'A', text[ASCII_count]);
}

I chose to put the input inside of the while loop rather than outside of it as I believed it the characters would be read in more easier that way.  I also changed my for loop iteration to read the actual letters by their capacity size instead of by their ASCII representation.  That was a major source of confusion to me.

The results look great.  What do you think? :)
Title: Re: The programming help thread!
Post by: nat on September 14, 2007, 09:04:17 AM
Great Job!

Although somehow I missed that you were having problems initially...  :?:
Title: Re: The programming help thread!
Post by: Dark Fact on September 14, 2007, 09:13:08 AM
How the hell did you miss it? :lol: Maybe your eye strain is finally getting the better of you. :shock: