Sunday, September 26, 2010

fstream in a nutshell

2 <- post your comments here

Imagine your little elementary brother asking you to help him with his assignment in mathematics. The instruction of their teacher was to get the average of a set of values. Because you feel the need to help your littler bro out, you glanced at his notebook and saw five sets of numbers to be averaged.

  1. 5 5 6 8
  2. 12 23 34 45
  3. 100 200 300 400
  4. 12 76 45 56
  5. 23 23 34 12
You say to yourself, "Hey, my little bro can handle these questions without breaking a sweat". But because you are a loving older brother/sister who wants to make his little bro's life easier than it already is... you went to your room, looked for your calculator and went back to your little bro's study table to give him the gadget. As you were giving it to him however, you noticed that he already had answered all of the questions, so you say to yourself, "Well I'll be, that's great, guess you won't be needing mr. calculator's help anymore". So you turned around, ready to return it to your room when you suddenly felt a heavy pull on the bottom part of your shirt.

It was your little bro, giving you the pitiful "doggy eyes" look, showing you his notebook as he flips the pages, saying in a desperate voice, "brother, what about the other 500 sets of numbers to be averaged??"...

FSTREAM WANTS TO MAKE YOU LIFE EASIER


Even if we make a program to get the averages of the list of number sets. It's almost expected that after we get a working program, the task is still "strenuous". If the program developed would have no loops we need to
  • compile the program
  • re-run the program 500 times
  • type the number sets 500 times
  • get results and copy them to your brother's notebook 500 times
or even if the program developed already incorporated in it the use of loops, we still have to
  • compile the program
  • enter number sets 500 times
  • get results and copy them to your brother's notebook 500 times
with using fstream functionality however the steps are reduced to
  • write all the number sets in a separate text file
  • compile and run your program once only
  • copy the results to your brother's notebook, (or technically your brother has to do all the copying, right??)


HOW DOES IT DO THAT?


take a look at this sample code below

  1. #include <iostream>
  2. #include <fstream>

  3. using namespace std;

  4. int main()
  5. {
  6. int num1, num2, num3, num4;
  7. ifstream infiler;
  8. infiler.open("assignmentOfLittleBro.txt");
  9. if (infiler.is_open())
  10. {
  11. while (!infiler.eof())
  12. {
  13. infiler >> num1 >> num2 >> num3 >> num4;
  14. //get the average of the four numbers and output it (left as an exercise)
  15. }
  16. }
  17. infiler.close();
  18. return 0;
  19. }
It somewhat works this way, God declared us to be to be of type human, having declared as such we find ourselves capable of some kind of skill or functions like singing, cooking our own meals, using our hands to produce things etc. Now notice that in line 9 infiler is declared to be of type ifstream , being declared as such infiler is granted the capability to function both as a bridge and a container.

How is it a bridge?? Line 10 tells us that infiler has a skill .open() that allows it to open files located in the same folder or directory. Line 11 also demonstrates how infiler checks if the text file to be opened (orange text) was successfully opened using .is_open(). Being multi-talented infiler also was given the talent to check if we've already reached the end of the file we've just opened (Line 13) using .eof(). The while loop is there since we need to iterate through the data present in assignmentOfLittleBro.txt which would look something like this (you're the one to encode it).

5 5 6 8
12 23 34 45
100 200 300 400
12 76 45 56
23 23 34 12

How is it a container?? Line 15 could be translated as "get four integers from assignmentOfLittleBro.txt and store them into four variables namely the ones we've declared". combining Line 15 with Line 13 it would pretty much translate to "until we reach the end of the file get four integers from assignmentOfLittleBro.txt and store them into four variables namely the ones we've declared". Isn't this great??? Now try the following things out...
  • file streaming will not work without #include <iostream> why is that???
  • suppose you have the following input values
10 20 30 40 50
1 2 3 4 5 6 7 8 9 0
123 234 345 456
  • will the code still work?? Why?? Why not??
P.S. - infiler could be any other name, you can have it as ifstream myVariable or whatever you fancy

Goodluck with your little brother! Make him proud. =]

-oOo-

Tuesday, September 21, 2010

TYPECAST: more than just a band

0 <- post your comments here

"Unlonely nights, romantic moments" *kidding*

Just a quick note directed to a particular firstyear who says he is engaging problems concerning the CAPITALIZATION OF LETTERS (and the reverse of it).

But before that let me just say that We all feel pleased about your eagerness to do programming stuff. We commend you for that and do continue keeping on. Cheers!

Ok, moving on, there is such a thing in C++ programming called TYPECASTING (a roughly similar JAVA tool is PARSING) that allows you to force a declared variable into a data type you desire at Run time. To address the question on capitalizing your letters, think of it as
  • forcing the input lowercase letter to be a number
  • to which you will add a value
  • where that value, when converted back to a letter
  • will output its corresponding Uppercase equivalent.
Before you continue reading the article, it would aid that you search or google up STANDARD ASCII CHARACTER SET in the interweb so as to understand what is written above in bullets,

IMPORTANT: the ascii set is the link between your lowercase and uppercase letters.

take this code fragment for instance,

char sampleLetter = 'j';
int sampleLetterBecomesInt = (int)sampleLetter; //typecasting happens here
sampleLetterBecomesInt = sampleLetterBecomesInt - 32;
cout << (char)sampleLetterBecomesInt; //and here
______________________________________

  • Why do we need to subtract by 32???
  • after line 2, what now is the value of variable sampleLetterBecomesInt
  • after line 4, what now is the output in the console (or terminal)
  • ___________________________________


    Once your done, you're ready for exercises. If you've followed the article on strings (older posts) then you are already equipped with necessary logic to do the following.
    • given a string variable with the value of "your_name"(i mean really your name as in Jessa or Martin) written in lowercase, Traverse the string capitalizing the first letter of your name.
    [martin becomes Martin and jessa becomes Jessa]
    • then you may try the reverse
    [martin becomes martiN and jessa becomes jessA]
    • then you may try CamelCaps in compound words
    [watermelon becomes WaterMelon and cheezepaper becomes CheezePaper]
    • or do it in regular intervals
    [wavylookingtext becomes WaVyLoOkInGtExT]
    // odds become capital evens are retained

    -o0o-

    Saturday, September 4, 2010

    C++

    0 <- post your comments here

    here's a good reference: http://www.google.com

    One more thing you need to learn about programming: You do not simply copy paste another one's solution to a problem. Sometimes, you have to find another solution for your solution.

    Why don't we all calm down here.

    0 <- post your comments here

    So okay, the previous authors have been teaching you about the basics of programming. You know the basics, but do you have the attitude? Programming simply involves logic but concentrating on logic would also entail a lot of patience and determination. We know that you are all eager to start creating c++ programs. We know it's exciting to do awesome stuffs with a couple of codes input in your computers. But, before you program, here are some tips to bring you to the top of your game.
    1. Before you program, you must read the problem. How can you even deliver if you do not know what you are solving.
    2. Analyze the problem. Most beginners commit mistakes in this part. They are very eager to do programs but they commit mistakes because they are solving the problem the wrong way.
    3. Be patient, think first before you start typing. Nuff said, the more mistakes you make, the more effort you'll be exerting to correct it.
    4. Type the source code as if it's error proof. Yeah, so that you won't be spending a lot of time with troubleshooting. Well, we don't expect our programs to run at the first try but this tip will surely help, trust me, I've been there.
    5. When you're program works, do not spread your source code. Think of it as a trophy. Let the others go through the painstaking process that you've been through (lol). But yeah, if they need help, give them some advice, but not give them the code. Share your helping hand, but not the entire arm.

    Well I guess that's all for my first post in this site. I hope I've shared enough. Til the next time!

    Oh wait. you can visit my blog here too: ohaiithere.blogspot.com
    Disclaimer: my personal site isn't about programming ^___^


    -rexstatic

    "Modulo" - A Roman Numeral Secret Recipe

    0 <- post your comments here

    Roman Numerals Anyone.,.,??

    After reading this post, you are expected to understand and realize.
    • What "HARDCODED" programs are
    • and that You can make a "BETTER" algorithm than the one presented
    Let's begin.

    Here is the code for printing the Roman Numeral equivalent of Integers from 11 - 39 only.


    1. #include <iostream>
    2.
    3. using namespace std;
    4.
    5. int main ()
    6. {
    7. int numberToBeRomanized = 0;
    8. int zeroToNine = 0;
    9. int printX = 0; int countToX = 0;
    10. cout << "::HARDCODED romanizer::" << endl;
    11. cout << "romanizes numbers from 10 - 39 only" << endl;
    12. for(;;)
    13. {
    14. cout << "Enter Number To Be Romanized: ";
    15. cin >> numberToBeRomanized;
    16.
    17. if (numberToBeRomanized == 999)
    18. break;
    19.
    20. printX = numberToBeRomanized / 10;
    21.
    22. while (countToX < printX)
    23. {
    24. cout << "X";
    25. countToX++;
    26. if (countToX == printX)
    27. {
    28. zeroToNine = numberToBeRomanized %= 10;
    29. if (zeroToNine == 0)
    30. cout << "" << endl;
    31. if (zeroToNine == 1)
    32. cout << "I" << endl;
    33. if (zeroToNine == 2)
    34. cout << "II" << endl;
    35. if (zeroToNine == 3)
    36. cout << "III" << endl;
    37. if (zeroToNine == 4)
    38. cout << "IV" << endl;
    39. if (zeroToNine == 5)
    40. cout << "V" << endl;
    41. if (zeroToNine == 6)
    42. cout << "VI" << endl;
    43. if (zeroToNine == 7)
    44. cout << "VII" << endl;
    45. if (zeroToNine == 8)
    46. cout << "VIII" << endl;
    47. if (zeroToNine == 9)
    48. cout << "IX" << endl;
    49. } //end the if's
    50. } //end while
    51. countToX = 0;
    52. } //end for
    53. return 0;
    54. }



    Tracing the whole program flow is left as an exercise... However, important points to be highlighted are as follows.
    • Notice Line 12. This is the "FOREVER" loop. Mainly because it loops forever. Until the programmer specifies a certain sentinel value, that makes it stop. In the program it was set to be 999 (Line 17). Try it out for yourself change the sentinel value from 999 to whatever integer you like.
    • Notice also Line 26. This condition just checks whether it's already the last iteration. If it is, then it prints out roman numeral equivalents from 0 (blank space) to 9 ("IX"). This is based on the observation that Roman Numeral End digits always fall in between these values so it is but proper to check them during the last iteration.
    • Line 51 as well. This line simply re-initializes the variable countToX to zero. The reason for this is line number 25, where we increment its value to get the number of X's to print. If we omit this code (try it), the program would correctly display the the Roman Numeral Equivalent of only the first number the user enters. Since during the next execution of the code it's value remains to be 1 or 2 or 3 depending on the first number you've entered.
    • Line 28 also is important. In the sense that after printing your X's, it checks what value from zero to nine is to be printed. Say if the user inputs 27, the value of variable zeroToNine would be 7 because 27 % 10 = 7. The resulting value gets checked and the program prints the string values specified for each zero to nine value.
    HARDCODED? WHAT DOES IT MEAN?...

    Line 11 would explain that. A program being hardcoded means that it could only address a portion of the whole problem it wishes to solve. Try running the program and inputting values from zero to nine.
    • What happens?
    • Why do you think it happened that way?
    • could you guess the single line of code to be added to correct the error?
    While you're at it you could also input numbers like 40, 70 or 89. This would give you rather inacceptable and funny looking roman numerals.

    EXPANDING THE HARDCODE...

    Attempting to make a program that would output roman numeral equivalents of integers that range from hundreds to thousands is actually a different thing. But if you want to follow through and edit the code above. Here's how to do it.
    • Line 20. This is the line that continually divides the input integer by ten. Which makes sense since the program only tries to convert integers in the given range. Try tweaking the program and add a code block that would divide the input integer by hundreds. Make another that would do it by thousands.
    • Line 22. Of course since you added two variables that would count how many are the number of hundreds and thousands the input number has, you should also add loops to process them.
    • Plus, as it had been stated, it only accomodates numbers from 11 - 39. so you have a lot of if statements to place correctly output "L's" "M's" and "D's". X's have been taken care of.
    NO THANKS I'LL MAKE MY OWN...

    Alrighty then that's good. Here are some of the suggested things to do.
    • Make Variables that would hold the value of the letters in them. like int X = 10, I = 1, V = 5 or int C = 100. And as you loop through the digits (visit the article regarding strings) check whether the value to be outputted is greater than the previous value. If yes, Swap the two and output the greater. and the loop continues.
    • Arrays would help. =]


    -o0o-
    nothing follows