ZH's software thread

Place to talk about all that new hardware and decaying software you have.

Moderator: General Mods

Post Reply
ZH/Franky

ZH's software thread

Post by ZH/Franky »

I said a while ago that I suck at programming, being a newbie and all, and that trying to learn C was a nightmare. So anyway, python was easier (for me, a newbie) to understand. I quickly started getting used to different concepts. Anyway, I won't tell you my life story; I tried my hands with C++ this time instead, and I'm making much better progress than last time I tried. I will be looking at arrays (what in python would be lists, tuples, or dictionaries), functions, etc. I will also be playing around with different data types.

What I'm interested in right now is trying to create a user-driven database:
the user inputs series' of data containing forenames, surnames, dob's and titles (Mr, Mrs, or Ms). I will also try figuring out how to perform validation checks of said data that gets inputted. I will also try getting the C++ program I write to do this job, to also write this data to a file (name of which is specified by the user), and have an option to read from a file with this recorded data. Still, I've only recently got into C++, so it will take a while until I'm able to write a program like this.

Well, basically I am starting to *really* like programming, much more so than when I first tried to learn how to write code.

Anyway, the program below isn't exactly complex or anything (and doesn't do anything useful), but it's the first *actual* program that I have *ever* written in C++:

Code: Select all

#include <iostream>

using namespace std;

int main()
{
    int num;
    int loop;
    int lowest;
    int highest;
    cout << "Enter number (0 to finish): ";
    cin >> num;
    if ( num == 0 ) {
         return 0;
         }
    highest = num;
    lowest = num;
    cout << "Enter number (0 to finish): ";
    cin >> num;
    if ( num == 0 ) {
         return 0;
         }
    else if ( num > highest ) {
         highest = num;
         }
    else if ( num < highest ) {
         lowest = num;
         }
    cout<<"Lowest number "<< lowest <<" and highest number "<< highest <<"\n";
    loop = 1;
    while ( loop == 1 ) {
          cout << "Enter number (0 to finish): ";
          cin >> num;
          if ( num == 0 ) {
               return 0;
               }
          else if ( num < highest ) {
               if ( num == 0 ) {
                    return 0;
                    }
               else if ( num < lowest ) {
                    lowest = num;
                    }
               }
          else if ( num > lowest ) {
               if ( num == 0 ) {
                    return 0;
                    }
               else if ( num > highest ) {
                    highest = num;
                    }
               }
          cout<<"Lowest number "<< lowest <<" and highest number "<< highest <<"\n";
          }
    cin.get();
}
Last edited by ZH/Franky on Tue Feb 10, 2009 9:55 pm, edited 2 times in total.
grinvader
ZSNES Shake Shake Prinny
Posts: 5632
Joined: Wed Jul 28, 2004 4:15 pm
Location: PAL50, dood !

Re: I now have a better chance at becoming l33t

Post by grinvader »

You can improve on this.

Lots of redundant parts that you can condense in a single loop.
Also, it seems not exactly GI proof. No output if any of the first 2 inputs are null ?
Redoing the loop would also take care of that.
皆黙って俺について来い!!

Code: Select all

<jmr> bsnes has the most accurate wiki page but it takes forever to load (or something)
Pantheon: Gideon Zhi | CaitSith2 | Nach | kode54
funkyass
"God"
Posts: 1128
Joined: Tue Jul 27, 2004 11:24 pm

Post by funkyass »

A friend of mine once suggested putting his program into a binary tree.
Does [Kevin] Smith masturbate with steel wool too?

- Yes, but don’t change the subject.
ZH/Franky

Post by ZH/Franky »

Hey grin, thanks for the input, I'll try improving this based on your suggestions; what do you mean by "GI"? Also, what do you mean by "NULL"?

@funkyass: Forgive my ignorance, but what is a "binary tree"?

Well grin, I agree with you that parts of the code I posted are useless, and that some peices of code are needlessly repeated. I decided to make an attempt at cleaning up the code, and here is the result:

Code: Select all

#include <iostream>

using namespace std;

int main()
{
    int num;
    int loop;
    int lowest;
    int highest;
    int phase;
    loop = 0;
    phase = 0;    
    while ( loop == 0 ) {
        cout << "Enter number (0 to finish): ";
        cin >> num;
        if ( num == 0 ) {
      	   return 0;
           }
        if ( phase == 0 ) {
           highest = num;
   	       lowest = num;
   	       phase = 1;
   	       loop = 1;
   	       }
        else if ( phase == 1 ) {
    	   if ( num > highest ) {
        	   highest = num;
        	   }
           else if ( num < highest ) {
         	   lowest = num;
        	   }
           phase = 2;
           loop = 1;
    	   }
        else if ( phase == 2 ) {
    	   if ( num < lowest ) {
    		   lowest = num;
    		   loop = 1;
    		   }
    	   else if ( num > highest ) {
    		   highest = num;
    		   loop = 1;
    		   }
           }
        while ( loop == 1 ) {
              cout<<"Lowest number "<< lowest <<" and highest number "<< highest <<"\n";
              loop = 0;
              }
        }
}

EDIT:
Been messing around with functions, and I've got to say, the following code is awesome:
(too bad it doesn't work atm. need to fix it)

Code: Select all

#include <iostream>
using namespace std;
void def(){int highest,lowest,num,loop,phase;}
void ask(){cout<<"Enter number (0 to finish): ";cin>>num;}
void hi(){highest=num;}
void lo(){lowest=num;}
void nbl(){if(num<lowest){lo();}}
void noh(){if(num>highest){hi();}}
void res(){cout<<"Lowest number"<<lowest<<"and highest number"<<highest<<"\n";}
int main(){def();loop=0;phase=0;
 while(loop==0){ask();if(num==0){return 0;}
  if(phase==0){hi();lo();phase=1;loop=1;}
  if(phase==1){noh();nbl();phase=2;loop=1;}
  if(phase==2){nbl();noh();loop=1;}
  while(loop==1){res();loop=0;}}}
odditude
Official tech support dood
Posts: 2118
Joined: Wed Jan 25, 2006 7:57 am

Post by odditude »

that is horrendous.

even if you had an idea what scope was, using a function in place of a single, simple statement is like using a ladle to eat your cereal - awkward and just plain stupid.
Why yes, my shift key *IS* broken.
Deathlike2
ZSNES Developer
ZSNES Developer
Posts: 6747
Joined: Tue Dec 28, 2004 6:47 am

Post by Deathlike2 »

That code makes baby Jesus cry.
Continuing [url=http://slickproductions.org/forum/index.php?board=13.0]FF4[/url] Research...
gllt
NO VOWELS >:[
Posts: 753
Joined: Sun Aug 31, 2008 12:59 pm
Location: ALABAMA
Contact:

Post by gllt »

Appropriate != Title
funkyass
"God"
Posts: 1128
Joined: Tue Jul 27, 2004 11:24 pm

Post by funkyass »

Franky wrote:@funkyass: Forgive my ignorance, but what is a "binary tree"?
something you need to learn about dude...
Does [Kevin] Smith masturbate with steel wool too?

- Yes, but don’t change the subject.
ZH/Franky

Post by ZH/Franky »

Deathlike2 wrote:That code makes baby Jesus cry.
Hey, at least I didn't fuck up as badly as when I tried to write the same program in python (again, messsing around with functions in the process):

Code: Select all

lowest = 0
highest = 0
num = 0
loop = 1
re = "You entered", num, "...Lowest number so far is", lowest, "and highest is", highest
def ask():
 num = input("Enter number (0 to finish): ")
def num0():
 if num == 0:
  loop = 0
def lo():
 lowest = num
def hi():
 highest = num
def ifnuh():
 if num < highest:
  lo()
def ifnoh():
 if num > highest:
  hi()
def ifr():
 ifnuh()
 ifnoh()
 loop = 2
def ifs1():
 lo()
 hi()
 ask()
 num0()
 ifr()
def num1():
 if num < lowest:
  lo()
def num2():
 if num < lowest:
  num0()
  num1()
def ifr1():
 if num < highest:
  num2()
 elif num > lowest:
  ifs2()
 print re
def ifr2():
 if num < 0 or num > 0:
  ifs1()
def ifs2():
 if num == 0:
  loop = 0
 elif num > highest:
  hi()
def ifslave():
 if loop == 1:
  ifr2()
 elif loop == 2:
  ifr1()
def ifmaster():
 if loop == 1:
  ifslave()
 elif loop == 2:
  ifslave()
def ifsecond():
 num0()
 ifmaster()
def ifstates():
 if loop == 1:
  ifsecond()
 elif loop == 2:
  ifsecond()
def prog():
 ask()
 ifstates()
def prog2():
 ask()
 ifstates()
while loop == 1:
 prog()
while loop == 2:
 prog2()
Fucking awesome, right!?
If baby Jesus saw this code, he'd probably say "fuck sinlessness" and kill himself!

*ahem*
anyway, I'm a beginner. I'm allowed to make mistakes.
grinvader
ZSNES Shake Shake Prinny
Posts: 5632
Joined: Wed Jul 28, 2004 4:15 pm
Location: PAL50, dood !

Post by grinvader »

Franky wrote:what do you mean by "GI"?
Garbage In, aka rabid monkey, aka final user.
An unhealthy proportion of bugs in your average program comes from lack of such proofing.
Also, what do you mean by "NULL"?
Try printf("%d", NULL);
anyway, I'm a beginner. I'm allowed to make mistakes.
Not really.
皆黙って俺について来い!!

Code: Select all

<jmr> bsnes has the most accurate wiki page but it takes forever to load (or something)
Pantheon: Gideon Zhi | CaitSith2 | Nach | kode54
Deathlike2
ZSNES Developer
ZSNES Developer
Posts: 6747
Joined: Tue Dec 28, 2004 6:47 am

Post by Deathlike2 »

The thread title screams for an edit.

Being a beginner really doesn't allow for mistakes, because fucking up is a sure sign you'll cause deeper shit to potentially happen.
Continuing [url=http://slickproductions.org/forum/index.php?board=13.0]FF4[/url] Research...
whicker
Trooper
Posts: 479
Joined: Sat Nov 27, 2004 4:33 am

Post by whicker »

sigh.

yay. post a code snippet. watch everyone tear it to pieces with their "better" way of doing it.

Of course, beginners aren't allowed to make mistakes on their own isolated system. Write your code as if it were to run alongside a nuke plant monitoring system. Be perfect or don't do it at all!

You need a license to code on your own home system.
I.S.T.
Zealot
Posts: 1325
Joined: Tue Nov 27, 2007 7:03 am

Post by I.S.T. »

whicker wrote:sigh.

yay. post a code snippet. watch everyone tear it to pieces with their "better" way of doing it.

Of course, beginners aren't allowed to make mistakes on their own isolated system. Write your code as if it were to run alongside a nuke plant monitoring system. Be perfect or don't do it at all!

You need a license to code on your own home system.
Agreed. Franky doesn't really deserve this.
blackmyst
Zealot
Posts: 1161
Joined: Sun Sep 26, 2004 8:36 pm
Location: Place.

Post by blackmyst »

Deathlike2 wrote:Being a beginner really doesn't allow for mistakes,
Ok what.

Are you serious?
[size=75][b]Procrastination.[/b]
Hard Work Often Pays Off After Time, but Laziness Always Pays Off Now.[/size]
AamirM
Regen Developer
Regen Developer
Posts: 533
Joined: Sun Feb 17, 2008 8:01 am
Contact:

Post by AamirM »

Hi,
whicker wrote:Write your code as if it were to run alongside a nuke plant monitoring system. Be perfect or don't do it at all!
Deathlike2 wrote:Being a beginner really doesn't allow for mistakes
C'mon people, give guy some credit for at least trying. If you don't make mistakes you never really learn and gain experience.
Franky wrote:Python is crap.
At least it faithfully crashes when you fuck up something instead of doing something weird/obscure like in C.

And just out of curiosity, where are you learning this stuff from?

stay safe,

AamirM
ZH/Franky

Post by ZH/Franky »

AamirM wrote:And just out of curiosity, where are you learning this stuff from?
For most of my learning (when it comes to C++), I often visit http://cprogramming.com/ -- they have lots of wonderful tutorials for both C and C++.
I'm thinking of picking up a good book (in print) on C++ from somewhere like Amazon. Anyone know any good books that are well-detailed and up to date? (2007 (preferrably 2008) and onwards).
grinvader wrote:Try printf("%d", NULL);
Umm, printf() is for C right? I'm using C++.



Btw guys, I wrote something else today:

Code: Select all

#include <iostream>
using namespace std;
int main()
{
    double num,total,loop,mem,phase;
    phase = 1;
    loop = 1;
    while ( loop == 1 ) {
          if ( phase == 1 ) {
               total = 1;
               cout << "\n";
               cout << "Enter decimal integer to find factorial of (-1 to finish): ";
               cin >> num;
               mem = num;
               phase = 0;         
               }
          if ( num == -1 ) {
               return 0;
               }
          total = num * total;
          loop = 2;
          while ( loop == 2 ) {
                if ( num < -1 ) {
                     cout << "Mathematical error: " << mem << " cannot be factorialized!\n";
                     phase = 1;
                     loop = 1;
                     }
                num = num - 1;
                total = num * total;
                if ( num == 2 ) {
                     cout << total;
                     phase = 1;
                     loop = 1;
                     }
                }
          }
}
This will find the factorial of a given number. It has a bug -- enter 0, 1, or 2 and it will report that the number cannot be factorialized, though we all know that 0! = 1, 1! = 1, and 2! = 2. Doesn't really matter since most people probably wouldn't ask the program to find the factorial of 0 1 or 2, but it's a bug nontheless.
Still, it's better than beforehand when entering 0, 1 or 2 made this program crash! :shock:

It really is quite useful that at college, in addition to computing I am also studying Physics and Double Mathematics; when I learn a new thing in either Maths or Physics (like some physics/mathematical law) I can try and write that in code (right now as you know, I'm trying to learn C++).

What I might try to do at some time, is write a program to find the coefficient of a number to a certain power. E.g. if you had (6x + 3)^3, find the coefficient of the x^3 term. (possibly using pascal's triangle).
Maybe I might have to use arrays to do this?
Wow, thinking about it, that would be a lot of code.

Like, today I got set homework to write an algorithm (in MS VB.NET) that will convert a given binary number to decimal, and another algorithm to convert a given decimal number to binary. I already figure out the algorithm in my head, I just need to put it into actual code.
Once I've written it in VB, I'll try and write it in C++ (I wasn't told to also do it in C++, but I want to).
Man, I love programming.


Well, here's my idea for binary to decimal:
*declare bin as a string
*declare count as an integer
*declare maxthing as integer
*ask the user to input binary number (store in bin)
*count number of characters in bin (store in count)
*maxthing = 2 ^ count
*reverse the order of the characters in bin
*look at each character in bin (from left to right), and if 1, then maxthing equals maxthing minus 2^(position_on_row_of_bin - 1 ), and if 0, then maxthing equals maxthing minus 0.
Do this until done the last character in bin
*display value of maxthing

And here's my idea for decimal to binary
declare bin as string
declare num as float
declare point as float
declare intr as float
*ask for decimal input (integer) -- store in num
!!!loop until num = 0
- *num = num / 2
- *intr = (decimal point of num)
- *if intr = 0.5 then put character "1" to string, else put character "0" to string
*and then when num = 0, reverse the order of the characters in bin
*then display the string "bin".

What do you guys think of these two algorithms?

Now, what really cooks my noodle is hamming codes, and grey codes. Once I get my head around them, I'm sure it will be easy to understand, but man those are complicated.

grinvader wrote:Garbage In, aka rabid monkey, aka final user.
An unhealthy proportion of bugs in your average program comes from lack of such proofing.
Ah, now I understand. Yes, enter any non-number (e.g. "monkey" or just any single character like [, etc) when prompted for a number on any of the two non-b0rked programs I posted, and it will enter an infinite loop. By "GI proofing", are you telling me that I need to implement some kind of "validation check" for these things?
Last edited by ZH/Franky on Tue Oct 21, 2008 12:02 am, edited 1 time in total.
Deathlike2
ZSNES Developer
ZSNES Developer
Posts: 6747
Joined: Tue Dec 28, 2004 6:47 am

Post by Deathlike2 »

blackmyst wrote:
Deathlike2 wrote:Being a beginner really doesn't allow for mistakes,
Ok what.

Are you serious?
Not really, but global variables and functions that are supposed to have parameters to make them globally more useful make me vomit.
Continuing [url=http://slickproductions.org/forum/index.php?board=13.0]FF4[/url] Research...
Starman Ghost
Trooper
Posts: 535
Joined: Wed Jul 28, 2004 3:26 am

Post by Starman Ghost »

Franky wrote: Umm, printf() is for C right? I'm using C++.
It's called C++ because it is C + extra stuff. Everything from C works in c++.
[code]<Guo_Si> Hey, you know what sucks?
<TheXPhial> vaccuums
<Guo_Si> Hey, you know what sucks in a metaphorical sense?
<TheXPhial> black holes
<Guo_Si> Hey, you know what just isn't cool?
<TheXPhial> lava?[/code]
Gil_Hamilton
Buzzkill Gil
Posts: 4294
Joined: Wed Jan 12, 2005 7:14 pm

Post by Gil_Hamilton »

AamirM wrote:Hi,
whicker wrote:Write your code as if it were to run alongside a nuke plant monitoring system. Be perfect or don't do it at all!
Deathlike2 wrote:Being a beginner really doesn't allow for mistakes
C'mon people, give guy some credit for at least trying. If you don't make mistakes you never really learn and gain experience.
To be fair, I'm pretty sure whicker was mocking Deathlike.



And regardless of his myriad other blunders, comic and otherwise, I'm officially giving Franky credit here.
He's going beyond the average "magic box" computer user, and learning how to bend it over a table and make it scream. Or whatever the hell else he wants, if electrocoitus isn't his thing.
MisterJones
Trooper
Posts: 387
Joined: Fri Jul 30, 2004 6:25 am
Location: Mexico
Contact:

Post by MisterJones »

Starman Ghost wrote:
Franky wrote: Umm, printf() is for C right? I'm using C++.
It's called C++ because it is C + extra stuff. Everything from C works in c++.
This is not exactly true, actually. While it does share some of its syntax, and there is a port of the C89 standard library, they are quite diferent languages when you work purely on either (C99 has some stuff that is not compatible with C++, and vice versa). So while yeah, printf and such are supported because of the standard library implementation, I'd rather go all the way using the C++ libraries (iostream over stdio, among others).
_-|-_
DOLLS (J) [!]
ZNES Developer
Posts: 215
Joined: Mon Aug 02, 2004 11:22 pm

Post by DOLLS (J) [!] »

Franky wrote:Well, here's my idea for binary to decimal:
*declare bin as a string
*declare count as an integer
*declare maxthing as integer
*ask the user to input binary number (store in bin)
*count number of characters in bin (store in count)
*maxthing = 2 ^ count
*reverse the order of the characters in bin
*look at each character in bin (from left to right), and if 1, then maxthing equals maxthing minus 2^(position_on_row_of_bin - 1 ), and if 0, then maxthing equals maxthing minus 0.
Do this until done the last character in bin
*display value of maxthing
?!

Code: Select all

int pow2(int n) {
    int result = 1;
    for (int i = 0; i < n; i++)
        result *= 2;
    return result;
}

...

int sum = 0;
for (int i = 0; i < bin.length(); i++)
    sum += (bin[i] == '1')? pow2(bin.length() - i - 1) : 0;

...
Example 2 (shifts):

Code: Select all

int main()
{
    string bin = "1010101010101000111001100";
    int num= 0;

    for (int i = 0; i < bin.length(); i++)
        num |= (bin[i] == '1')? 1 << (bin.length() - i - 1) : 0;

    cout << num << endl;
    return 0;
}
Franky wrote: And here's my idea for decimal to binary
...
Ok, that's more reasonable.


BTW: Python isn't crap.
h4tred

Post by h4tred »

By "GI proofing", are you telling me that I need to implement some kind of "validation check" for these things?
Yes, some exception handling would be nice indeed. Its not nice not reacting gracefully to errors....
Python is crap.
I have to agree with Aamir and DOLLZ. From personal experience, Python is most certainly not crap. I'm interested in why you said that, or are you just saying it because you find it too difficult.
I've learned a little bit of C++ from my computing tutor at college (well, one of them; I have 2 tutors -- one of them I have on Mondays and Fridays, and the other I have on thursdays -- I learn the C++ from the one I have on Mondays and Fridays). There is also a small section on C++ in my computing textbook. Though, right now we're focusing on MS Visual Basic .NET, and will do for some time.
For most of my learning (when it comes to C++), I often visit http://cprogramming.com/ -- they have lots of wonderful tutorials for both C and C++.
I'm thinking of picking up a good book (in print) on C++ from somewhere like Amazon. Anyone know any good books that are well-detailed and up to date? (2007 (preferrably 2008) and onwards).
And where did you learn that Python dialect you wrote? Seriously, I recommend you read "Python Programming: A Introduction To Computer Science" by John Zelle. His book should help you in writing more decent Python code.
ZH/Franky

Post by ZH/Franky »

DOLLS (J) [!] wrote:
Franky wrote:Well, here's my idea for binary to decimal:
*declare bin as a string
*declare count as an integer
*declare maxthing as integer
*ask the user to input binary number (store in bin)
*count number of characters in bin (store in count)
*maxthing = 2 ^ count
*reverse the order of the characters in bin
*look at each character in bin (from left to right), and if 1, then maxthing equals maxthing minus 2^(position_on_row_of_bin - 1 ), and if 0, then maxthing equals maxthing minus 0.
Do this until done the last character in bin
*display value of maxthing
?!

Code: Select all

int pow2(int n) {
    int result = 1;
    for (int i = 0; i < n; i++)
        result *= 2;
    return result;
}

...

int sum = 0;
for (int i = 0; i < bin.length(); i++)
    sum += (bin[i] == '1')? pow2(bin.length() - i - 1) : 0;

...
Example 2 (shifts):

Code: Select all

int main()
{
    string bin = "1010101010101000111001100";
    int num= 0;

    for (int i = 0; i < bin.length(); i++)
        num |= (bin[i] == '1')? 1 << (bin.length() - i - 1) : 0;

    cout << num << endl;
    return 0;
}
Franky wrote: And here's my idea for decimal to binary
...
Ok, that's more reasonable.


BTW: Python isn't crap.
Oh, well thanks for the suggestions. So THAT's why I have had problems with strings in C++; I've used "char something" to do what I thought was declaring a string. >_<
Well, this certainly helps me in another area too --> I'm trying to see if I can implement password protection in my code (not that I'd release my software with DRM measures, but it's always interesting to see if I can actually do it).
h4tred wrote:Yes, some exception handling would be nice indeed. Its not nice not reacting gracefully to errors....
"Exception handling". I'll have to look into that. Thanks for the advice.

I can do a lot of things with python, and I know that it is very powerful, and will let you perform almost any task, but I like my code to be compiled.
I learned python from the following site: http://www.sthurlow.com/python/
The only real reason that I don't like python, is because in python it is mandatory that you indent your code.
odditude
Official tech support dood
Posts: 2118
Joined: Wed Jan 25, 2006 7:57 am

Post by odditude »

Franky wrote:The only real reason that I don't like python, is because in python it is mandatory that you indent your code.
if more languages did this, visually proofing code would be much easier.

it would seriously impair obfuscated C contests, though :D
Why yes, my shift key *IS* broken.
ZH/Franky

Post by ZH/Franky »

Well, I'm not saying that indenting isn't a good thing. I just don't like being forced to do it.
odditude wrote:
Franky wrote:The only real reason that I don't like python, is because in python it is mandatory that you indent your code.
if more languages did this, visually proofing code would be much easier.

it would seriously impair obfuscated C contests, though :D
WHY YES, YOUR SHIFT KEY *is* BROKEN. :D
Post Reply