• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 12:16
CEST 18:16
KST 01:16
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6Code S RO8 Preview: herO, Zoun, Bunny, Classic7
Community News
Weekly Cups (June 23-29): Reynor in world title form?12FEL Cracov 2025 (July 27) - $8000 live event14Esports World Cup 2025 - Final Player Roster14Weekly Cups (June 16-22): Clem strikes back1Weekly Cups (June 9-15): herO doubles on GSL week4
StarCraft 2
General
Weekly Cups (June 23-29): Reynor in world title form? StarCraft Mass Recall: SC1 campaigns on SC2 thread The SCII GOAT: A statistical Evaluation How does the number of casters affect your enjoyment of esports? Esports World Cup 2025 - Final Player Roster
Tourneys
FEL Cracov 2025 (July 27) - $8000 live event HomeStory Cup 27 (June 27-29) WardiTV Mondays SOOPer7s Showmatches 2025 $200 Biweekly - StarCraft Evolution League #1
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers [G] Darkgrid Layout
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma Mutation # 477 Slow and Steady
Brood War
General
ASL20 Preliminary Maps BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion StarCraft & BroodWar Campaign Speedrun Quest Unit and Spell Similarities
Tourneys
[Megathread] Daily Proleagues [BSL20] GosuLeague RO16 - Tue & Wed 20:00+CET The Casual Games of the Week Thread [BSL20] ProLeague LB Final - Saturday 20:00 CET
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Path of Exile What do you want from future RTS games? Beyond All Reason
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Stop Killing Games - European Citizens Initiative Trading/Investing Thread Russo-Ukrainian War Thread
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread Korean Music Discussion
Sports
2024 - 2025 Football Thread Formula 1 Discussion NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
from making sc maps to makin…
Husyelt
Blog #2
tankgirl
Game Sound vs. Music: The Im…
TrAiDoS
StarCraft improvement
iopq
Heero Yuy & the Tax…
KrillinFromwales
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 802 users

C++ revision help!

Blogs > konadora
Post a Reply
Normal
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 14:47:08
June 28 2009 14:36 GMT
#1
I want to start off by saying that I'm quite noob with C++ programming, and I need to revise everything in 4 hours' time. Guides online have more terms introduced than explained, so I'm hoping I'll get more luck here.

First, what's the difference between:

int main()


and

void main()


? I keep seeing int main() being used more often in examples, but in school, I've been only using void main().

Second, why is this invalid?

#include <iostream>
using namespace std;

void main()
{
int x;
cout << "Please enter an integer." << endl;
cin >> x >> endl;

cout << "You have entered "x << endl;

}


I get these errors:

1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2146: syntax error : missing ';' before identifier 'x'
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2563: mismatch in formal parameter list
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2568: '<<' : unable to resolve function overload


As well as this message while debugging:
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(974): could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )'
1> with
1> [
1> _Elem=wchar_t,
1> _Traits=std::char_traits<wchar_t>
1> ]
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(966): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(940): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )'


Fixed!

+ Show Spoiler [Fixed ver] +
#include <iostream>
using namespace std;

void main()
{
int x;
cout << "Please enter an integer." << endl;
cin >> x;

cout << "You have entered " << x << endl;

}


I need to revise right from the basics, learning how to do sorts (bubble sorts, insertion sorts, quick sorts, binary search) as well as learning how to use weights, strings etc.

This is one I did quite some time ago, but I didn't revise and completely forgot the reason behind it:

#include <iostream>
#include <string>
using namespace std;

void main() {
char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
int weight[8] = { 0,2,7,6,5,4,3,2 };
string nric;
int sum=0; // init cumulative sum to zero

// get NRIC input
cout << "Enter NRIC: ";
getline (cin,nric);
cout << nric << endl;
// calculate check digit
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0')*weight[i];
}
cout << sum << endl;
int checkdigit = 11 - (sum%11);
// check if the user's NRIC check digit matches to confirm valid nric
if (digit[checkdigit]==nric[8])
cout << "valid NRIC number" << endl;
else
cout << "Invalid NRIC number" << endl;
}


Help would be greatly appreciated!!!

POGGERS
Divinek
Profile Blog Joined November 2006
Canada4045 Posts
June 28 2009 14:38 GMT
#2
without ever doing c++ and knowledge from other languages i would say the first question is int and void are return types you know int returns an integer and void doesnt return anything
Never attribute to malice that which can be adequately explained by stupidity.
Oh goodness me, FOX tv where do you get your sight? Can't you keep track, the puck is black. That's why the ice is white.
AoN.DimSum
Profile Blog Joined September 2008
United States2983 Posts
June 28 2009 14:39 GMT
#3
using int function will give the result as a integer, that is why return 0 is used a lot when using int main();
But using void main() gives no result im pretty sure. That is how i understand it. ( I think im sure)
by my idol krokkis : "U better hope Finland wont have WCG next year and that I wont gain shitloads of skill, cause then I will wash ur mouth with soap, little man."
AcrossFiveJulys
Profile Blog Joined September 2005
United States3612 Posts
June 28 2009 14:42 GMT
#4

#include <iostream>
using namespace std;

void main()
{
int x;
cout << "Please enter an integer." << endl;
cin >> x >> endl;

cout << "You have entered "x << endl;

}


you need to put another "<<" before x on the last line. so change the last line to

cout << "You have entered " << x << endl;
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 14:42 GMT
#5
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?
POGGERS
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 14:44 GMT
#6
Okay I got the short program to work, I foolishly used cin >> x >> endl; instead of cin >> x;

#include <iostream>
using namespace std;

void main()
{
int x;
cout << "Please enter an integer." << endl;
cin >> x;

cout << "You have entered " << x << endl;

}
POGGERS
AcrossFiveJulys
Profile Blog Joined September 2005
United States3612 Posts
June 28 2009 14:47 GMT
#7
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 14:49 GMT
#8
Oh I see, so it's just that int main() allows you to identify whether your program has an error or not, but void main() can't?
POGGERS
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
June 28 2009 15:01 GMT
#9
void main() should never be used as the main function should ALWAYS return a value

I thought everyone that?!
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 15:05 GMT
#10
On June 29 2009 00:01 Revabug wrote:
void main() should never be used as the main function should ALWAYS return a value

I thought everyone that?!

Would you mind explaining a bit more? I already stated that I'm quite noob with C++
POGGERS
Tracil
Profile Blog Joined September 2005
Australia505 Posts
Last Edited: 2009-06-28 15:07:37
June 28 2009 15:06 GMT
#11
When you're doing a small project, as is typical for a lot of uni work, what your main function returns basically won't matter. Albeit obviously it's better practice to use int, and bad habits are bad.
Shooting
sidesprang
Profile Joined January 2009
Norway1033 Posts
June 28 2009 15:06 GMT
#12
never use void main. Its oldschool bad programming.
Float like a butterfly, sting like a bee.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 15:09:06
June 28 2009 15:08 GMT
#13
Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?
POGGERS
treason
Profile Joined February 2009
Germany72 Posts
Last Edited: 2009-06-28 15:11:01
June 28 2009 15:09 GMT
#14
On June 28 2009 23:36 konadora wrote:
Show nested quote +
#include <iostream>
#include <string>
using namespace std;

void main() {
char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
int weight[8] = { 0,2,7,6,5,4,3,2 };
string nric;
int sum=0; // init cumulative sum to zero

// get NRIC input
cout << "Enter NRIC: ";
getline (cin,nric);
cout << nric << endl;
// calculate check digit
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0')*weight[i];
}
cout << sum << endl;
int checkdigit = 11 - (sum%11);
// check if the user's NRIC check digit matches to confirm valid nric
if (digit[checkdigit]==nric[8])
cout << "valid NRIC number" << endl;
else
cout << "Invalid NRIC number" << endl;
}


char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J'
int weight[8] = { 0,2,7,6,5,4,3,2 };
same with integer values
cout << "Enter NRIC: ";
getline (cin,nric);

here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric.
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0' )*weight[i];
}

this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0.
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 15:10 GMT
#15
The only thing int main does is use the int you return as a parameter for ExitProcess (or exit, which is basically a wrapper for ExitProcess). void main will always return 0.
Minimal effort.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 15:13 GMT
#16
On June 29 2009 00:09 treason wrote:
Show nested quote +
On June 28 2009 23:36 konadora wrote:
#include <iostream>
#include <string>
using namespace std;

void main() {
char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
int weight[8] = { 0,2,7,6,5,4,3,2 };
string nric;
int sum=0; // init cumulative sum to zero

// get NRIC input
cout << "Enter NRIC: ";
getline (cin,nric);
cout << nric << endl;
// calculate check digit
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0')*weight[i];
}
cout << sum << endl;
int checkdigit = 11 - (sum%11);
// check if the user's NRIC check digit matches to confirm valid nric
if (digit[checkdigit]==nric[8])
cout << "valid NRIC number" << endl;
else
cout << "Invalid NRIC number" << endl;
}


char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J'
int weight[8] = { 0,2,7,6,5,4,3,2 };
same with integer values
cout << "Enter NRIC: ";
getline (cin,nric);

here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric.
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0' )*weight[i];
}

this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0.

I need help with explanation on the 'arrays' part, I can't find the notes online on my school's e-learning platform. Step-by-step explanation would help so much, I would love you for life
POGGERS
tec27
Profile Blog Joined June 2004
United States3696 Posts
June 28 2009 15:15 GMT
#17
On June 28 2009 23:47 AcrossFiveJulys wrote:
Show nested quote +
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.

Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.
Can you jam with the console cowboys in cyberspace?
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 15:16 GMT
#18
On June 29 2009 00:15 tec27 wrote:
Show nested quote +
On June 28 2009 23:47 AcrossFiveJulys wrote:
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.

Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.


You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)
Minimal effort.
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
Last Edited: 2009-06-28 15:20:57
June 28 2009 15:17 GMT
#19
oops
AcrossFiveJulys
Profile Blog Joined September 2005
United States3612 Posts
June 28 2009 15:20 GMT
#20
On June 29 2009 00:08 konadora wrote:
Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?


you really need to read your textbook. float, double, int, are all variable types. this is a very basic concept, and you won't get far asking such questions here.
Revabug
Profile Blog Joined June 2009
United Kingdom147 Posts
June 28 2009 15:20 GMT
#21
Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?


They're just data types, they can be used to return but they're not 'return data types'
AcrossFiveJulys
Profile Blog Joined September 2005
United States3612 Posts
June 28 2009 15:22 GMT
#22
On June 29 2009 00:16 Uligor wrote:
Show nested quote +
On June 29 2009 00:15 tec27 wrote:
On June 28 2009 23:47 AcrossFiveJulys wrote:
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.

Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.


You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)


That was my understanding as well. To his defense, of course, if you are using a compiler which does not do this, you might have problems. But overall this is a very petty concept.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 15:25:20
June 28 2009 15:23 GMT
#23
My teachers didn't explain any of these differences, just gave us terms, they're like, 'put these here and here, you get a program. now try it'.

That's why... :S

What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.
POGGERS
ms291052
Profile Joined April 2008
United States24 Posts
June 28 2009 15:24 GMT
#24
On June 28 2009 23:49 konadora wrote:
Oh I see, so it's just that int main() allows you to identify whether your program has an error or not, but void main() can't?


This is essentially true. Some people prefer to always use int as it is "good form." Honestly though, if you don't understand the difference yet, which one you use will make no difference at all.

As for the second program, you read in a NRIC, which is apparently some sort of barcode or something. You then check to see if it's valid by using a check digit, a computable extra number added to the string:

int weight[8] = { 0,2,7,6,5,4,3,2 };
for (int i=1; i<=7; i++)
sum = sum + ( nric[i] - '0' ) * weight[ i ];

// nric[ i ] is the ith character of the nric
// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0.
// You then multiply each digit of the nric by some pre-determined "weight" and add them up.
// This algorithm is arbitrary, but as long as it's reproducible any check-digit algorithm is fine.

char digit[ 12 ]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J' };
int checkdigit = 11 - ( sum % 11 );
if( digit[ checkdigit ] == nric[ 8 ] )

// You then take the resulting sum and use modulus arithmetic to reduce it to the range [ 1, 11 ]
// Then you look up the character with that index (from 1 to 11) in the "digit" array to get the 'secret' character that belongs with this string. If they match, you then output saying so. Otherwise you output an error.

Examples:

If your NRIC is 12345678H then your sum is 2*2 + 3*7 + 4*6 + 5*5 + 6*4 + 7*3 + 8*2 = 135 (Note that you ignore the first character, since its index is 0 and i starts from 1)
Then you see that 135 % 11 = 3, so your "check digit" is 11 - 3 = 8.
So you then look up 8 in the digit[] array to get 'H'.
You compare the calculate check digit with the check digit at the end of the number. Lo and behold, a match!

Now, if your NRIC is 93843248B then your sum is 2*3 + 3*8 + 4*4 + 5*3 + 6*2 + 7*4 + 8*8 = 165.
Then you see that 165 % 11 = 0, so your check digit is 11 - 0 = 11.
You look up digit[ 11 ] to get 'J', and compare that to the check digit on the end of the NRIC. They don't match, so clearly I inputted my number wrong.
treason
Profile Joined February 2009
Germany72 Posts
Last Edited: 2009-06-28 15:30:07
June 28 2009 15:28 GMT
#25
On June 29 2009 00:13 konadora wrote:
Show nested quote +
On June 29 2009 00:09 treason wrote:
On June 28 2009 23:36 konadora wrote:
#include <iostream>
#include <string>
using namespace std;

void main() {
char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
int weight[8] = { 0,2,7,6,5,4,3,2 };
string nric;
int sum=0; // init cumulative sum to zero

// get NRIC input
cout << "Enter NRIC: ";
getline (cin,nric);
cout << nric << endl;
// calculate check digit
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0')*weight[i];
}
cout << sum << endl;
int checkdigit = 11 - (sum%11);
// check if the user's NRIC check digit matches to confirm valid nric
if (digit[checkdigit]==nric[8])
cout << "valid NRIC number" << endl;
else
cout << "Invalid NRIC number" << endl;
}


char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};
creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J'
int weight[8] = { 0,2,7,6,5,4,3,2 };
same with integer values
cout << "Enter NRIC: ";
getline (cin,nric);

here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric.
for (int i=1; i<=7; i++) {
sum = sum + (nric[i]-'0' )*weight[i];
}

this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0.

I need help with explanation on the 'arrays' part, I can't find the notes online on my school's e-learning platform. Step-by-step explanation would help so much, I would love you for life

An array is a field of values. Lets say, you want to save 5 numbers:
int number1, number2, number3, number4, number5;
number1 = 0;
number2 = 3;
number3 = 7;
number4 = 12;
number5 = 1;

Thats really annoying, you have to write alot and you can make some mistakes if you are sleepy :D
Thats why arrays were invented:

int example[5];
example[0] = 0;
example[1] = 3;
example[2] = 7;
example[3] = 12;
example[4] = 1;

Thats also to long, you can write it in a shorter way:
int example[] = {0,3,7,12,1};
the first line int example[5]; declares a field of integer values with the length of 5, in the next 5 lines i put some values into this field. Now, 5 values are saved into this field, and you can access its content via the [ ] operator.
If you want to print the first number, you can do:
cout >> number1>> endl;
and with the array:
cout >> example[0] >> endl;
Another good thing about arrays is, that you can use a for-loop the access all contents of the field:
for(int i = 0; i<=4; i++){
cout >> example[i] >> endl;
}

will write:
0
3
7
12
1

on the screen.


konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 15:36:08
June 28 2009 15:32 GMT
#26
@ms291052:

// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0.
// You then multiply each digit of the nric by some pre-determined "weight" and add them up.

Why is the -0 necessary? (Great first post btw, thanks lol)

@treason:
so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]?

Also, this part

for(int i = 0; i<=4; i++){
cout >> example[i] >> endl;
}


Means that something like:

First, display the 0th line's number, and since it's not greater than example[4], display 0+1 (making it 1th) line's number, and continue until it reaches i = 4 (where it cannot exceed i = 4 and ends there), right?
POGGERS
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 15:38 GMT
#27
On June 29 2009 00:32 konadora wrote:
@ms291052:

Show nested quote +
// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0.
// You then multiply each digit of the nric by some pre-determined "weight" and add them up.

Why is the -0 necessary? (Great first post btw, thanks lol)

@treason:
so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]?


The character '0' has a different value than int 0 (char '0' is in fact 48 int, '1' is 49 etc). But when you subtract the character with '0', you essentially do -48. So when the character is '1' (49), it becomes 49-48 = 1.
Minimal effort.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 15:40 GMT
#28
On June 29 2009 00:38 Uligor wrote:
Show nested quote +
On June 29 2009 00:32 konadora wrote:
@ms291052:

// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0.
// You then multiply each digit of the nric by some pre-determined "weight" and add them up.

Why is the -0 necessary? (Great first post btw, thanks lol)

@treason:
so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]?


The character '0' has a different value than int 0 (char '0' is in fact 48 int, '1' is 49 etc). But when you subtract the character with '0', you essentially do -48. So when the character is '1' (49), it becomes 49-48 = 1.

Oooh, okay thanks, didn't know that!
POGGERS
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 15:48 GMT
#29
My next question:

What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.
POGGERS
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 15:49 GMT
#30
On June 29 2009 00:48 konadora wrote:
My next question:

Show nested quote +
What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.


float or double.
Minimal effort.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 15:53 GMT
#31
Isn't double for numbers with decimal points? What's the difference between float and double?

(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)
POGGERS
tec27
Profile Blog Joined June 2004
United States3696 Posts
June 28 2009 15:56 GMT
#32
On June 29 2009 00:16 Uligor wrote:
Show nested quote +
On June 29 2009 00:15 tec27 wrote:
On June 28 2009 23:47 AcrossFiveJulys wrote:
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.

Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.


You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)

I'm sorry, but you're wrong except for very specific compilers. Microsoft's compiler does this, but the standards do not support that. It was merely done to make bad code that they/other people had written in the past still work.

If you hop over to g++, however, you'll find that you can't even compile a program with 'void main':
voidmain.cpp:1: error: '::main' must return 'int'


Now, what is within the standards is to auto-return 0 for main functions declared as type int (IE: if no return statement is specified inside). While this is still bad practice, it should work on all standards-compliant compilers.

In short, don't encourage someone to not follow standards on a simple matter like this just because a certain compiler will fix the mistake for them. Its incredibly bad practice, and this is the kind of thing that, even though its small, will make lots of people have zero respect for you and your code.
Can you jam with the console cowboys in cyberspace?
tec27
Profile Blog Joined June 2004
United States3696 Posts
Last Edited: 2009-06-28 16:01:46
June 28 2009 15:58 GMT
#33
On June 29 2009 00:53 konadora wrote:
Isn't double for numbers with decimal points? What's the difference between float and double?

(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)

Both double and float are for numbers with decimal points. A double has more precision than a float (IE: can store longer decimals), but is also therefore larger in memory.

Edit: Also, you probably don't need to use a floating-point format at all, you can just plug the 5/9 into the calculation itself.

IE: int celsius = (int)((farenheit - 32) * 5 / 9);

Should work (although it will be truncated to an integer).
Can you jam with the console cowboys in cyberspace?
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 16:01 GMT
#34
On June 29 2009 00:58 tec27 wrote:
Show nested quote +
On June 29 2009 00:53 konadora wrote:
Isn't double for numbers with decimal points? What's the difference between float and double?

(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)

Both double and float are for numbers with decimal points. A double has more precision than a float (IE: can store longer decimals), but is also therefore larger in memory.

Oh okay, understand now.

Thanks for all the responses so far, I just need to refresh my memory since I did practice quite a bit... a few months ago. Currently doing an exercise, will post questions once again here if I get stuck, can't say this enough but thanks again!
POGGERS
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 16:03 GMT
#35
On June 29 2009 00:53 konadora wrote:
Isn't double for numbers with decimal points? What's the difference between float and double?

(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)



double and float are for numbers like 1.234, yes. The difference between double and float is float is 32 bit and double is 64 bit.

Maybe I misunderstood your question, you wanted to know what datatype you should use in an algorithm to convert Farenheit temperature into centigrade and viceversa? Or did you want to know how to output a fraction in the console?

On June 29 2009 00:56 tec27 wrote:
Show nested quote +
On June 29 2009 00:16 Uligor wrote:
On June 29 2009 00:15 tec27 wrote:
On June 28 2009 23:47 AcrossFiveJulys wrote:
On June 28 2009 23:42 konadora wrote:
I don't really quite understand the concept of 'returning an integer', what does it mean?

Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?


no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.

if you make main void, then it has no return type, and will always return 0 to the caller.

Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.


You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)

I'm sorry, but you're wrong except for very specific compilers. Microsoft's compiler does this, but the standards do not support that. It was merely done to make bad code that they/other people had written in the past still work.

If you hop over to g++, however, you'll find that you can't even compile a program with 'void main':
Show nested quote +
voidmain.cpp:1: error: '::main' must return 'int'


Now, what is within the standards is to auto-return 0 for main functions declared as type int (IE: if no return statement is specified inside). While this is still bad practice, it should work on all standards-compliant compilers.

In short, don't encourage someone to not follow standards on a simple matter like this just because a certain compiler will fix the mistake for them. Its incredibly bad practice, and this is the kind of thing that, even though its small, will make lots of people have zero respect for you and your code.


It is true that it is compiler specific (I use MSVS08 and I was under the impression kona used this as well, hence the windows explanation of what happens with the exitcode). I apologize because I used "the compiler" instead of specifying the compiler I was talking about, this made it seem like I was belittling your knowledge of compiler specifics.
Minimal effort.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 16:08 GMT
#36
Maybe I misunderstood your question, you wanted to know what datatype you should use in an algorithm to convert Farenheit temperature into centigrade and viceversa?


Yup, which datatype.

Also, fyi, I'm using Microsoft Visual C++ Express Edition.
POGGERS
tec27
Profile Blog Joined June 2004
United States3696 Posts
June 28 2009 16:12 GMT
#37
Also, sorry if I'm coming off as rude, Uligor. I just think its a really bad idea to teach newer programmers to use 'void main()' before they even know how it affects anything, since its super-easy to learn the other way at the beginning, but somewhat harder to fix old habits later on.
Can you jam with the console cowboys in cyberspace?
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 16:13 GMT
#38
Okay, I've managed to complete the exercise, using this:

#include <iostream>
using namespace std;

int main()
{
double c,f;
cout << "Please enter the temperature in Centigrade." << endl;
cin >> c;
f = ((c*1.8)+32);
cout << "The temperature is " << f << " degrees Farenheit." << endl;

cout << "Please enter the temperature in Farenheit." << endl;
cin >> f;
c = ((f-32)*5/9);
cout << "The temperature is " << c << " degrees Centigrade." << endl;

return 0;
}


But I want the user to choose which one he's inputting first (whether he's going to input Farenheit or Centigrade), and use that, and end the program. Which loop do I use, and how?
POGGERS
tec27
Profile Blog Joined June 2004
United States3696 Posts
Last Edited: 2009-06-28 16:20:44
June 28 2009 16:20 GMT
#39
I don't think you need to use a loop for that, just use an if/else statement. Just input a character to decide which one to use or whatever and then check it:


if(myChar == 'c' ) {
// do Celsius -> Farenheit calculation
}
else if(myChar == 'f' ) {
// do Farenheit -> Celsius calculation
}
else {
// Tell the user to follow instructions, better luck next time
}
Can you jam with the console cowboys in cyberspace?
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 16:21:59
June 28 2009 16:21 GMT
#40
What is the myChar?

Or is that the 'character'? lol
POGGERS
tec27
Profile Blog Joined June 2004
United States3696 Posts
June 28 2009 16:24 GMT
#41
Yeah, thats just the variable you'd be inputting their answer to.
Can you jam with the console cowboys in cyberspace?
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 16:29 GMT
#42
I don't quite get how to use it, I got this -
#include <iostream>
using namespace std;

int main()
{
double c,f;
cout << "Please choose whether you are entering the temperature in Centigrade (c) or Farenheit (f)." << endl;
if(myChar == 'c'){
f = ((c*1.8)+32);
cout << "The temperature is " << f << " degrees Farenheit." << endl;
}
else if(myChar == 'f'){
c = ((f-32)*5/9);
cout << "The temperature is " << c << " degrees Centigrade." << endl;
}
return 0;
}


With these errors:

1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(8) : error C2065: 'myChar' : undeclared identifier
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(12) : error C2065: 'myChar' : undeclared identifier
POGGERS
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
June 28 2009 16:35 GMT
#43
On June 29 2009 00:49 Uligor wrote:
Show nested quote +
On June 29 2009 00:48 konadora wrote:
My next question:

What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.


float or double.


yes

at least one of the two numbers must be a float or double, or you must explicitly cast one to a double <static_cast> or integer division will be performed instead.

SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 16:38 GMT
#44
On June 29 2009 01:29 konadora wrote:
I don't quite get how to use it, I got this -
Show nested quote +
#include <iostream>
using namespace std;

int main()
{
double c,f;
cout << "Please choose whether you are entering the temperature in Centigrade (c) or Farenheit (f)." << endl;
if(myChar == 'c'){
f = ((c*1.8)+32);
cout << "The temperature is " << f << " degrees Farenheit." << endl;
}
else if(myChar == 'f'){
c = ((f-32)*5/9);
cout << "The temperature is " << c << " degrees Centigrade." << endl;
}
return 0;
}


With these errors:

Show nested quote +
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(8) : error C2065: 'myChar' : undeclared identifier
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(12) : error C2065: 'myChar' : undeclared identifier


The code in this case would be

#include <iostream>
using namespace std;

int main()
{
double value;
char myChar;

cout << "Please enter C (Centigrade) or F (Farenheit) followed by the appropriate value" << endl;
cin >> myChar >> value;

if(myChar == 'C')
cout << "The temperature is " << (value*1.8)+32 << " degrees Farenheit." << endl;
else if(myChar == 'F')
cout << "The temperature is " << (value-32)*5/9 << " degrees Centigrade." << endl;
else
cout << "Please insert a correct prefix" << endl;

return 0;
}


Please note how I replaced double f/c with double value and how I moved the calculations to inside the cout << instruction.
The example input for this piece of code would be "F 1.42". (note: this would be a rather unpleasant temperature)
Minimal effort.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-28 16:42:50
June 28 2009 16:41 GMT
#45
The char is the same as 'int', except it is not just integers, but characters, that's all, right?

Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?

Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.
POGGERS
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 28 2009 16:45 GMT
#46
On June 29 2009 01:41 konadora wrote:
The char is the same as 'int', except it is not just integers, but characters, that's all, right?


char is 8 bit, int is 32 bit (though for int it's compiler specific). I think this might go a bit too far for now, you should use char to save single-byte characters (e.g. 'e', '0', etc).

On June 29 2009 01:41 konadora wrote:Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?


Yeah, it's basically to remove unnecessary variables.
Minimal effort.
GHOSTCLAW
Profile Blog Joined February 2008
United States17042 Posts
Last Edited: 2009-06-28 16:46:55
June 28 2009 16:46 GMT
#47
oops.
PhotographerLiquipedia. Drop me a pm if you've got questions/need help.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 16:50 GMT
#48
Thanks for all the help for this noob here, I don't think I can keep awake anymore, already drank 4 cups of coffee. Will wake up in 6 hours' time and continue from there, going to get some sleep (almost 1am here). Thanks all once again!
POGGERS
okayokes
Profile Joined March 2004
United States39 Posts
June 28 2009 16:50 GMT
#49
On June 29 2009 01:41 konadora wrote:
The char is the same as 'int', except it is not just integers, but characters, that's all, right?

Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?

Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.



char holds one ASCII character iirc. If you want a sentence you should use a string. Though you could also use a character array.

char myChar[] = {'H', 'e', 'l', 'l', 'o'};

string myString = "Hello";
-,-
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
Last Edited: 2009-06-28 16:59:17
June 28 2009 16:55 GMT
#50
On June 29 2009 01:35 fusionsdf wrote:
Show nested quote +
On June 29 2009 00:49 Uligor wrote:
On June 29 2009 00:48 konadora wrote:
My next question:

What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.


float or double.


yes

at least one of the two numbers must be a float or double, or you must explicitly cast one to a double <static_cast> or integer division will be performed instead.



With the code "(value-32)*5/9" (value being double) the compiler (MSVS08) generated FPU instructions for 5/9, so in this case it was not necessary. However I see your concern because compilers like to precalculate things.
Minimal effort.
Divinek
Profile Blog Joined November 2006
Canada4045 Posts
June 28 2009 17:07 GMT
#51
are you in uni for a class or something? if you are im a bit confused how you dont understand any of this. If it's a highschool class or something then maybe i get it but some of this stuff you are asking is like first few weeks of learning. I'm just honestly curious not trying to be a dick
Never attribute to malice that which can be adequately explained by stupidity.
Oh goodness me, FOX tv where do you get your sight? Can't you keep track, the puck is black. That's why the ice is white.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 28 2009 17:20 GMT
#52
I'm in high school, started 3 months ago, but I had gotten sick around March (which was the period where my sudden burst in activeness on TL occurred), missing school for a month, after which I failed to revise enough lol.

Not to mention the one month summer break (which ended today) made me just slack all the way.
POGGERS
Scorch
Profile Blog Joined March 2008
Austria3371 Posts
June 28 2009 17:35 GMT
#53
Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you.
You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself.
unknown.sam
Profile Joined May 2007
Philippines2701 Posts
June 28 2009 17:53 GMT
#54
On June 29 2009 02:35 Scorch wrote:
Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you.
You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself.

this
"Thanks for the kind words, but if SS is the most interesting book you've ever read, you must have just started reading a couple of weeks ago." - Mark Rippetoe
AoN.DimSum
Profile Blog Joined September 2008
United States2983 Posts
June 28 2009 18:03 GMT
#55
http://cplusplus.com/ is a good site
by my idol krokkis : "U better hope Finland wont have WCG next year and that I wont gain shitloads of skill, cause then I will wash ur mouth with soap, little man."
okayokes
Profile Joined March 2004
United States39 Posts
Last Edited: 2009-06-28 18:23:06
June 28 2009 18:18 GMT
#56
cool site. C++ seems confusing at first but it gets alot easier over time. Certain things I'm trying to learn now are hard to get my head around. Like recursion <_>;

code like this can be hard to get a grip on (atleased for me):

void permute(string current, string rest)
{
if (rest == "")
{
cout << current << endl;
++counter;
}else{
for ( int i = 0; i < rest.length(); i++ )
{
string next = current + rest[i];
string remaining = rest.substr(0, i)
+ rest.substr(i+1);
permute(next, remaining);
}
}
}

the syntax itself is not the difficult aspect, but keeping track of every stack frame and how it unravels is difficult ~_~. There are some great stanford lectures posted up on youtube though! http://www.youtube.com/profile?user=stanforduniversity&view=playlists

Programming Methodology is the beginners course using mostly Java.
Programming Abstractions is the intermediate course using C++
Programming Paradigms is the advanced course which I haven't looked at.
-,-
DrLefTy
Profile Blog Joined June 2009
United States36 Posts
June 28 2009 18:53 GMT
#57
if you want to learn recursion, learn how to code in lisp or scheme.
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
Last Edited: 2009-06-28 20:59:03
June 28 2009 20:53 GMT
#58
On June 29 2009 01:41 konadora wrote:
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.


since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized.

Its really important to stay consistent throughout your code.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
eci
Profile Joined July 2008
Germany45 Posts
June 28 2009 21:45 GMT
#59
back to the question void main() and int main() - int main() starts an application which returns an int number ( -2^31..(2^31-1) ) while void main() always returns 0. How this returned value depends on your operating system, on linux you can see that result code e.g. by "echo $?" on bash command line.
I think void main() is also not in the recent standard any more, so if you do not know for sure just use "int main()" and don't forget to return a value ( return 0; - you could also write return -1; if an error happend - but its kind of old school )

Btw: This question is rather unimportant - try to write more code - implement some algorithms ( e.g. bread death search in a graph ) - use stl standard library - use external librarys like boost

hf in coding
Vorwaerts!
liquorice
Profile Joined August 2008
United States170 Posts
June 28 2009 23:19 GMT
#60
On June 29 2009 05:53 fusionsdf wrote:
Show nested quote +
On June 29 2009 01:41 konadora wrote:
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.


since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized.

Its really important to stay consistent throughout your code.


camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour.
fuck yeah zerglings!
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-06-29 01:01:49
June 29 2009 00:40 GMT
#61
On June 29 2009 02:35 Scorch wrote:
Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you.
You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself.

I understand that myself, but I haven't really been taught all the reasoning and concepts, and for my test, I'll have to write a code myself.

Lol I've managed to push my test to wednesday, woot
POGGERS
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
June 29 2009 04:08 GMT
#62
On June 29 2009 08:19 virLudens wrote:
Show nested quote +
On June 29 2009 05:53 fusionsdf wrote:
On June 29 2009 01:41 konadora wrote:
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.


since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized.

Its really important to stay consistent throughout your code.


camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour.


Hungarian Notation. I've always disliked it
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
Cambium
Profile Blog Joined June 2004
United States16368 Posts
June 29 2009 05:52 GMT
#63
On June 29 2009 13:08 fusionsdf wrote:
Show nested quote +
On June 29 2009 08:19 virLudens wrote:
On June 29 2009 05:53 fusionsdf wrote:
On June 29 2009 01:41 konadora wrote:
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.


since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized.

Its really important to stay consistent throughout your code.


camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour.


Hungarian Notation. I've always disliked it


Oh cool, I didn't even know it was called the Camel notation. I started with Hungarian Notation, and it's ultra lame
When you want something, all the universe conspires in helping you to achieve it.
Bill307
Profile Blog Joined October 2002
Canada9103 Posts
June 29 2009 07:44 GMT
#64
I feel like giving a lesson on data type basics.


8 bits = 1 byte, by the way. If you don't already know this, then repeat this to yourself 10 times, because I will interchange between bits and bytes constantly. E.g. if I say "32 bits" and then "4 bytes" then you need to recognize instantly that I'm talking about the same amount.


When you declare a variable, your compiler will set aside some region in memory (the computer's RAM) for that variable. Whenever you use that variable, you are accessing or modifying that region.

byte and char are both 8-bit (1-byte) variables: they occupy 8 bits in memory. Although they have different uses, in memory they look the same. E.g. the byte 65 and the char 'A' look exactly the same in memory: 65.

int and long are 16-bit and 32-bit variables, respectively. They store #s as integers. They can store both positive and negative integers. In memory, the int 65 might look like this: 0 65. Notice it occupies 2 bytes. Similarly, the long 65 might look like this: 0 0 0 65. If the number is too big to be stored in a single byte, then it spills over into the next byte, allowing you to store larger numbers.

Think of it like base-10 digits. A single digit can store only the numbers 0 to 9. Anything higher than 9 and you need 2 or more digits. Same thing with bytes, except it's base-256. You can store 0-255 in a single byte: anything higher than 255 and you need 2 or more bytes.

Base-10 example, counting from 8 to 12:
0 8
0 9
1 0
1 1
1 2

Base-256 (bytes) example, counting from 254 to 258:
0 254
0 255
1 0
1 1
1 2

If you can't figure out the pattern here, then look up number systems with different bases.

int and long can store negative numbers, too, but that's a lesson for another day. (It's actually pretty simple, if you understand binary and if it's explained correctly.)

If you're wondering what happens when you try to store a number that's too large in a byte, int, or long, then try it for yourself and see what happens (don't worry, it won't break anything).

float and double are 32-bit and 64-bit variables, respectively. These store numbers in floating point format, which is basically scientific notation. At this point in time, you might as well use doubles. But if you were to make, say, a game, where speed can be important, then you would use only floats in your program.


Pointers, when you start to use them (and die by them), take up 32 bits in memory. They're used to point to some location in memory, like where a variable is stored. Don't even try to learn how to use these until you understand a lot of simpler concepts first.

Structs and Classes take up varying amounts of memory, depending on what data they contain.


Hopefully now you understand variables a bit better.
Smix *
Profile Blog Joined January 2009
United States4549 Posts
June 29 2009 07:56 GMT
#65
Good luck on your exam kona
TranslatorBe an Optimist Prime, Not a Negatron // twitter @smixity
Superbia
Profile Blog Joined April 2008
Netherlands8889 Posts
June 29 2009 08:37 GMT
#66
On June 29 2009 16:44 Bill307 wrote:
int and long are 16-bit and 32-bit variables, respectively.


The size of int is actually compiler specific; on 32+ bit machines, int is usually 32 bit, which is what I think applies to konadora.
Minimal effort.
MasterOfChaos
Profile Blog Joined April 2007
Germany2896 Posts
June 29 2009 08:41 GMT
#67
Bill your sizes are usually true on 16 Bit systems. On 32 Bit systems int is usually 32 bit. And the C++ standard promises even less.
On 32 Bit VS afaik byte/char=8bit, short=16bit, int/long=32 bit, long long=64 Bit. And of course each of them is available as signed and unsigned.
LiquipediaOne eye to kill. Two eyes to live.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
June 29 2009 15:36 GMT
#68
Does it matter if I'm using a 64-bit edition of Vista?

Thanks a lot Bill, understand much clearer now, teacher hardly explained >__<

Thanks Smix
POGGERS
Bill307
Profile Blog Joined October 2002
Canada9103 Posts
June 29 2009 18:54 GMT
#69
Oh, thanks for the correction, guys.

So I guess the corrected version is:

short = 16-bit integer (-32768 to +32767)
long = 32-bit integer (approx. -2 billion to +2 billion)
int = 16- or 32-bit integer

Bah.

Well, I guess it's safest to assume int is only 16 bits, and use "long" if you need more than that.
MasterOfChaos
Profile Blog Joined April 2007
Germany2896 Posts
June 30 2009 07:20 GMT
#70
From the Stroustrup:
Sizes of C++ objects are expressed in terms of multiples of the size of a char , so by definition
the size of a char is 1 . The size of an object or type can be obtained using the sizeof operator. This is what is guaranteed about sizes of fundamental types:
1 = sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)
1 <= sizeof(bool) <= sizeof(long)
sizeof(char) <= sizeof(wchar_t) <= sizeof(long)
sizeof(float) <= sizeof(double) <= sizeof(long double)
sizeof(N) = sizeof(signed N) = sizeof(unsigned N)
where N can be char , shortint , int , or longint . In addition, it is guaranteed that a char has at least
8 bits, a short at least 16 bits, and a long at least 32 bits. A char can hold a character of the
machine’s character set.

Usual are:
char=8bit
short=16bit
int=16 or 32 bit
long=32 or 64 bit
long long=64 bit

There are also some typedefs with fixed size, but I forgot their names.
If I recall correctly there are also some size requirenments for pointers in relation to ints, but I forgot that too. On Win32 it is guaranteed that int,long are 32bit.
LiquipediaOne eye to kill. Two eyes to live.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-07-09 16:03:44
July 09 2009 15:59 GMT
#71
Bump

I've been doing something called the BMI test, here's my program:

#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
a = (w/(h*h));
if (w > 0, h > 0)
cout << "Your Body Mass Index is " << a << endl;
else
cout << "Invalid input." << endl;

if (0 < a < 20, w > 0, h > 0)
cout << "You have a low BMI." << endl;
else if (20 < a < 25, w > 0, h > 0)
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
return 0;
}


But the thing is, whenever I put in invalid numbers (-9001 or something), "You have a low BMI." STILL shows. What's the problem?

Will check this when I wake up in the morning, thanks in advance for any help! (going off to sleep;; )
POGGERS
50bani
Profile Blog Joined June 2009
Romania480 Posts
July 09 2009 16:15 GMT
#72
#include <iostream>
using namespace std;

void main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
a = (w/(h*h));
if (w > 0, h > 0)
{cout << "Your Body Mass Index is " << a << endl;
if (0 < a < 20, w > 0, h > 0)
cout << "You have a low BMI." << endl;
else if (20 < a < 25, w > 0, h > 0)
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else cout << "You have exceeded the healthy BMI range." << endl;
}
else
cout << "Invalid input." << endl;
}
I'm posting on twoplustwo because I have always been amazed at the level of talent that populates this site --- it's almost unparalleled on the Internet.
gokai
Profile Blog Joined August 2004
United States812 Posts
July 09 2009 16:17 GMT
#73
my god, i was good at math in highschool, so i thought i would be good at programming

boy was i wrong
Kau *
Profile Joined March 2007
Canada3500 Posts
July 09 2009 16:36 GMT
#74
Don't you need to use && or || for if statements?
Moderator
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 09 2009 16:43 GMT
#75
On July 10 2009 00:59 konadora wrote:
Bump

I've been doing something called the BMI test, here's my program:

Show nested quote +
#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
a = (w/(h*h));
if (w > 0, h > 0)
cout << "Your Body Mass Index is " << a << endl;
else
cout << "Invalid input." << endl;

if (0 < a < 20, w > 0, h > 0)
cout << "You have a low BMI." << endl;
else if (20 < a < 25, w > 0, h > 0)
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
return 0;
}


But the thing is, whenever I put in invalid numbers (-9001 or something), "You have a low BMI." STILL shows. What's the problem?

Will check this when I wake up in the morning, thanks in advance for any help! (going off to sleep;; )


This doesn't give you compilation errors?!

if (0 < a < 20, w > 0, h > 0)

You probably meant || or && right...?
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 09 2009 16:43 GMT
#76
On July 10 2009 01:36 Kau wrote:
Don't you need to use && or || for if statements?

yes, yes you do
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2009-07-09 16:49:11
July 09 2009 16:47 GMT
#77
You need to figure out the inequalities... you have 0 < a < 20 and 20 < a < 25, i.e. you don't cover the case where a == 20.


#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
// assuming you can't weight 0 kg and have 0 cm height ( h = 0 actually give you division by zero exception
if( w <= 0 || h <= 0 ) {
cout << "Invalid input." << endl;
return 0;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << endl;
}

if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

return 0;
}
When you want something, all the universe conspires in helping you to achieve it.
pinenamu
Profile Blog Joined September 2006
United States770 Posts
July 09 2009 16:55 GMT
#78
On July 10 2009 01:17 gokai wrote:
my god, i was good at math in highschool, so i thought i would be good at programming

boy was i wrong

lol same here, i crawled out of my c programming and mips r2000 class.. phew, never have to program again (hopefully)

good luck kona! i hate programming with a passion so looking at this stuff makes me gag lol.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 09 2009 22:37 GMT
#79
What does || do??
POGGERS
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 09 2009 22:40 GMT
#80
On July 10 2009 07:37 konadora wrote:
What does || do??


or...
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 09 2009 22:51 GMT
#81
Oh lol

Kk thanks
POGGERS
qrs
Profile Blog Joined December 2007
United States3637 Posts
Last Edited: 2009-07-09 22:54:14
July 09 2009 22:53 GMT
#82
'As per the American Heart Association, the beat of the Bee Gees song "Stayin' Alive" provides an ideal rhythm in terms of beats per minute to use for hands-only CPR. One can also hum Queen's "Another One Bites The Dust".' —Wikipedia
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
Last Edited: 2009-07-10 00:37:39
July 10 2009 00:37 GMT
#83
On July 10 2009 01:47 Cambium wrote:
You need to figure out the inequalities... you have 0 < a < 20 and 20 < a < 25, i.e. you don't cover the case where a == 20.


#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
// assuming you can't weight 0 kg and have 0 cm height ( h = 0 actually give you division by zero exception
if( w <= 0 || h <= 0 ) {
cout << "Invalid input." << endl;
return 0;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << endl;
}

if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

return 0;
}


ewww. I was always taught multiple return statements like that are frowned upon. to be honest, I'm not exactly sure what's considered acceptable in a professional environment. The code (if someone else is wondering) will still work perfectly, its just a matter of style.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 00:59 GMT
#84
Multiple return statements are acceptable in a professional environment.
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 01:52 GMT
#85
Okay I debugged the thing

#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
return 0;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
}
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

return 0;
}


And still, if I input two negative values, "You have a low BMI." still shows. What's the problem here?
POGGERS
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:00 GMT
#86
that's surprising... did you copy and paste or did you modify your source?
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
Last Edited: 2009-07-10 02:01:06
July 10 2009 02:00 GMT
#87
Modify

Oh, and happy birthday
POGGERS
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:01 GMT
#88
paste your source
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:01 GMT
#89
thanks for the hb
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 02:14 GMT
#90
#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
a = (w/(h*h));
if (w > 0, h > 0)
cout << "Your Body Mass Index is " << a << endl;
else
cout << "Invalid input." << endl;

if (0 < a < 20, w > 0, h > 0)
cout << "You have a low BMI." << endl;
else if (20 < a < 25, w > 0, h > 0)
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
return 0;
}
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
Last Edited: 2009-07-10 02:19:37
July 10 2009 02:18 GMT
#91
Are you still using commas in the 'if' statements? If you are then that's a problem. You have to use && for AND, || for OR

I guess you maybe just pasted the wrong source?
twitter: @terrancem
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 02:19 GMT
#92
Nope. The modified one is the one few posts above
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:20 GMT
#93
Ok. I got confused because your last post has the commas in it.
twitter: @terrancem
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:20 GMT
#94
What's your OS and what IDE/compiler are you using?

I'm amazed at its ability to interpret equalities and inequalities...

The problem with your code is that you don't terminate when you detected invalid inputs. The program continues to run and since two negatives give you a positive, you get "You have a low BMI".

After you terminate, you no longer need to check w > 0 and h > 0, as you have already done so.

#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
a = (w/(h*h));
if (w > 0, h > 0)
cout << "Your Body Mass Index is " << a << endl;
else {
cout << "Invalid input." << endl;
return 0;
}

if (0 < a < 20, w > 0, h > 0)
cout << "You have a low BMI." << endl;
else if (20 < a < 25, w > 0, h > 0)
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
return 0;
}
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 02:22 GMT
#95
Ooooh

I was wondering but, it's okay to have many 'return 0; ' statements?
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:23 GMT
#96
Now Cambium is modifying the source with the commas too. Hrmm, perhaps I'm still confused as to what your latest source is.
twitter: @terrancem
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:23 GMT
#97
I'm confused. Which source are you running?

There is no way you get anything beyond "invalid input" if you ran the code below...

if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
return 0;
}


catches any negative inputs.

+ Show Spoiler +


#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
return 0;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
}
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

return 0;
}
When you want something, all the universe conspires in helping you to achieve it.
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:26 GMT
#98
It's sort of ok. You can do it, but for beginning programming it's usually much easier to keep a single return for a function (main in this case).
twitter: @terrancem
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2009-07-10 02:27:05
July 10 2009 02:26 GMT
#99
Yes, it's okay to have multiple return statements... but this is better structurally, because your first if/else statement doesn't make too much sense.



#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
}
return 0;
}
When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 02:26 GMT
#100
OS = Vista 64-bit
Compiler = Visual C++ 2008 Express Edition

I'm using this one

#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
return 0;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
}
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

return 0;
}


The one I posted after that was the original before I modified it
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:28 GMT
#101
Also something you should get into a habit of doing is using proper variable names. You may not care about this now but it will help in the future. It also helps others (such as us trying to help you) read your code.

So "a" is body mass index you might call the variable "bmi" instead.
double bmi;

w and h are ok for variable names, but they could be better.
double weightKG;
double heightM;

Or something similar.
twitter: @terrancem
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:34 GMT
#102
Just in case you don't see it... here it is again...

On July 10 2009 11:26 Cambium wrote:
Yes, it's okay to have multiple return statements... but this is better structurally, because your first if/else statement doesn't make too much sense.

Show nested quote +


#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
}
return 0;
}

When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 02:36 GMT
#103
Cambium, I've the EXACT same program and yet, when I input a value like " -1023123", the 'You have a low BMI." message appears >__<
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:39 GMT
#104
I'm just checking things through notepad but Cambium's code looks good. Seems very strange that it's not working for you konadora so I'm downloading VS c++ express right now.
twitter: @terrancem
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
Last Edited: 2009-07-10 02:53:03
July 10 2009 02:52 GMT
#105
Ok I just ran it and I get the "Invalid input." as expected. I'm not sure what you might be doing konadora.

Maybe you are somehow running an old executable. Try a clean and build.
twitter: @terrancem
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 03:06 GMT
#106
Oh okay, nvm I found the error (different .cpp running -____- )

Sorry about that!
POGGERS
SonuvBob
Profile Blog Joined October 2006
Aiur21549 Posts
July 10 2009 03:20 GMT
#107
lol that's always fun. I FIXED IT, WHY ISN'T IT WORKING?!!
Administrator
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 10 2009 03:22 GMT
#108
On July 10 2009 12:20 SonuvBob wrote:
lol that's always fun. I FIXED IT, WHY ISN'T IT WORKING?!!


god. so much time wasted because of that and you can't even feel all that happy when you fix it.

"THIS held me up for 2 hours? THIS?!!?"
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 03:26 GMT
#109
yeah wtf man lol

Gotta continue revising
POGGERS
coltrane
Profile Blog Joined June 2008
Chile988 Posts
Last Edited: 2009-07-10 09:09:49
July 10 2009 09:08 GMT
#110
#include <iostream>
using namespace std;

int main()
{
double w, h;
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
// } why are you closing the if here

if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
} // closeit here
return 0;
}



look the correction and the comentary in bold.

there is something weird in the first scope too...

I now think that something... it seems that you believe that return will end the program. Thats not gonna happen, return 0; will jump out of the scope, not from the program. And that first return should be diferent to 0, 0 is NO ERROR.
Using stdlib.h (#include <stdlib.h>) you could use exit() function, like this "exit(1);" that will end the program and return 1 from main to std out





The thing is "a" cannot be empty, when you reserve the memory it has some value. So it will mostly have any value different to 1..24, then you always will see at std out "You have exceeded..."

Try this as an example:

#include <iostream>
using namespace std;

int main() {

int a;
double b;
char c;

cout << a << b << c;

return 0;

}
Jävla skit
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 10 2009 14:43 GMT
#111
a is defined as being w * h before it is actually used for anything. Since w and h are both initialized by the keyboard (and assuming valid keyboard input) a does not have to be given an initial value (neither do w or h since they are given an initial value before they are used.

To simplify it,

int a = 0;

is just as valid as

int a; //a's value is ????
a = 0;

As long as the assignment of 0 occurs before the variable is used, its fine.

As for exit, while you are correct it will work, its been out of favor and frowned upon (in both academic and most professional environments) for a long time. Because main is a function, when it returns, the function will end and it will return to the C++ environment, which will then end as a consequence. Having multiple return statements in main() will work just like it would in any function, although I disagree with it from a stylistic point of view.

here's a pretty cool discussion of multiple returns in C/C++: http://bytes.com/groups/c/617841-multiple-returns-functions
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 14:53 GMT
#112
coltrane's post is headache >__<

thanks fusionsdf

so I can just say double a = (w/(h*h)); ?
POGGERS
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
Last Edited: 2009-07-10 15:23:13
July 10 2009 15:15 GMT
#113
yes, as long as:

1) a isnt used any point before that line (since by saying double a you are declaring a)
2) w and h have already been declared and given values before that line.

As a matter of practice, its considered best to put all your variable declarations in one spot right at the top.

so while both

+ Show Spoiler [#1] +
#include <iostream>
using namespace std;

int main()
{
double w, h;
double a; //declaring a further on, so this declaration must be removed.
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
} else {
double a = (w/(h*h)); //declaring here. This is still valid and will execute properly.
cout << "Your Body Mass Index is " << a << "." << endl;
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
}
return 0;
}


+ Show Spoiler [#2] +
#include <iostream>
using namespace std;

int main()
{
double w, h; //all variables are declared in the same spot at the top of the function
double a;
cout << "Please enter your weight (in KG) and height (in meters)." << endl;
cin >> w >> h;
if (w <= 0 || h <= 0){
cout << "Invalid input." << endl;
} else {
a = (w/(h*h));
cout << "Your Body Mass Index is " << a << "." << endl;
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;
}
return 0;
}


are valid, #2 is considered better from a style point of view (both will execute exactly the same). Since you have to deal with potentially other people going through your code, or you taking a break, forgetting about this program and trying to understand what you were doing 3 month or even 3 years from now, you really want to make sure you are aware of what is considered good style and follow it whenever it makes sense to you.



Extra stuff



I want to add 2 more things that aren't obvious:

1) In Cambium's code he has:
if ( a > 0 && a < 20 )
cout << "You have a low BMI." << endl;
else if ( a > 20 && a < 25 )
cout << "You are within the healthy BMI range. Congratulations!" << endl;
else
cout << "You have exceeded the healthy BMI range." << endl;

For single line statements you do not need braces. That code is equivalent to:

if ( a > 0 && a < 20 )
{
cout << "You have a low BMI." << endl;
}
else if ( a > 20 && a < 25 )
{
cout << "You are within the healthy BMI range. Congratulations!" << endl;
}
else
{
cout << "You have exceeded the healthy BMI range." << endl;
}

Note that if there is more than one line, you cant omit the braces and still have it work. This will NOT do what is expected:

if ( a > 0 && a < 20 ) //line 1
cout << "You have a low BMI." << endl; //line 2
cout << "good bye!." << endl; //line 3

and will execute line 2 only if line 1 evaluates true and will execute line 3 in every case. When its more than one line, use braces. For multiple single line if else statements, omitting the braces is more often used, but check with your teacher to make sure thats the style she prefers.

2) the second point is that while

int a = 0;

and

int a;
a = 0;

is true for pretty much every primitive type (double, char, int, float), this does not work for c-strings

char c = "hello";

is valid.

char c;
c = "hello";

won't work (instead you would have to use a built in function)... this might not be an issue for you right now (its certainly not important for this program), but if you ever have a problem with c-strings like that, at least now you've seen it pointed out.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 10 2009 15:17 GMT
#114
Ah I see, clear about this now, thanks!!
POGGERS
yh8c4
Profile Blog Joined July 2009
108 Posts
July 10 2009 16:09 GMT
#115
some recommendations:

put your code on http://codepad.org. saves the formatting, has syntax coloring, and can even compile and run the code. i put your code to http://codepad.org/Yn2ulRxd and added some minor corrections (marked by comments).

good c++ resources:
http://www.parashift.com/c -faq-lite/
http://www.cplusplus.com/
channel ##c++ on irc.freenode.net

coltrane
Profile Blog Joined June 2008
Chile988 Posts
July 11 2009 09:22 GMT
#116
On July 10 2009 23:53 konadora wrote:
coltrane's post is headache >__<

thanks fusionsdf

so I can just say double a = (w/(h*h)); ?




first... why???


and second... no, you cant unless you define a after w and h. And if you do so and then you input 2 wrong values a will have the first value from its definition.




Jävla skit
konadora *
Profile Blog Joined February 2009
Singapore66156 Posts
July 11 2009 09:26 GMT
#117
Because I don't understand what you're talking about at all

I'm fairly new to C++ so...
POGGERS
coltrane
Profile Blog Joined June 2008
Chile988 Posts
Last Edited: 2009-07-11 20:43:27
July 11 2009 20:37 GMT
#118
okok;


copypaste this and compile it:

#include <iostream>
using namespace std;

int main() {

int a;
double b;
char c;

cout << a << b << c;

return 0;

}


When you run that shit you will realize that:

Variables always have a value, even when you dont asign any variable to it.

So, a good manner thing is to put some value in a variable like the a in your program
WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing

double a;

for the sentence

double a(0);

^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable.


I will rewrite your code.

+ Show Spoiler +

#include <iostream>
using namespace std;

int main()
{
       double w, h;
       double a(0);
       cout << "Please enter your weight (in KG) and height (in meters)." << endl;
       cin >> w >> h;
       if (w <= 0 || h <= 0){
             cout << "Invalid input." << endl;
             //this line is a comment. The compiler will skip it. ok, you asked for
             //2 values, if they dont fit the condition then we end just here,
             // and a is 0 right now.
       } else {
             a = (w/(h*h));
             cout << "Your Body Mass Index is " << a << "." << endl;

             //a has a new valid value. And then we ask:

             if ( a > 0 && a < 20 )
             cout << "You have a low BMI." << endl;
             else if ( a > 20 && a < 25 )
             cout << "You are within the healthy BMI range. Congratulations!" << endl;
             else
             cout << "You have exceeded the healthy BMI range." << endl;
       // i suppose you understand why we dont need brackets {} in this if
       }
       // if the inputed values are useless to us, then we are here.
       return 0;
}

Jävla skit
Jovan
Profile Joined August 2006
Canada65 Posts
July 11 2009 21:13 GMT
#119
On July 11 2009 01:09 yh8c4 wrote:
some recommendations:

put your code on http://codepad.org. saves the formatting, has syntax coloring, and can even compile and run the code. i put your code to http://codepad.org/Yn2ulRxd and added some minor corrections (marked by comments).

good c++ resources:
http://www.parashift.com/c -faq-lite/
http://www.cplusplus.com/
channel ##c++ on irc.freenode.net



If you are going to link C++ FAQ Lite, at least link C++ FQA Lite
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 12 2009 07:01 GMT
#120
On July 12 2009 05:37 coltrane wrote:
okok;


copypaste this and compile it:

Show nested quote +
#include <iostream>
using namespace std;

int main() {

int a;
double b;
char c;

cout << a << b << c;

return 0;

}


When you run that shit you will realize that:

Variables always have a value, even when you dont asign any variable to it.

So, a good manner thing is to put some value in a variable like the a in your program
WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing

double a;

for the sentence

double a(0);

^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable.


I will rewrite your code.

+ Show Spoiler +

#include <iostream>
using namespace std;

int main()
{
       double w, h;
       double a(0);
       cout << "Please enter your weight (in KG) and height (in meters)." << endl;
       cin >> w >> h;
       if (w <= 0 || h <= 0){
             cout << "Invalid input." << endl;
             //this line is a comment. The compiler will skip it. ok, you asked for
             //2 values, if they dont fit the condition then we end just here,
             // and a is 0 right now.
       } else {
             a = (w/(h*h));
             cout << "Your Body Mass Index is " << a << "." << endl;

             //a has a new valid value. And then we ask:

             if ( a > 0 && a < 20 )
             cout << "You have a low BMI." << endl;
             else if ( a > 20 && a < 25 )
             cout << "You are within the healthy BMI range. Congratulations!" << endl;
             else
             cout << "You have exceeded the healthy BMI range." << endl;
       // i suppose you understand why we dont need brackets {} in this if
       }
       // if the inputed values are useless to us, then we are here.
       return 0;
}



honestly I think that's overkill. As long as the programmer is smart enough to assign a value to the variable at some point before use (and hopefully a sanity check), there is no need to have every variable declaration include an assignment.

int a;
double b;
char c;

a = 0;
b = 0.0;
c = cin.get();

cout << a << b << c;

return 0;

There is no point declaring c with an initial value when you are just going to be getting it from the keyboard immediately after anyways.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
coltrane
Profile Blog Joined June 2008
Chile988 Posts
July 12 2009 09:25 GMT
#121
On July 12 2009 16:01 fusionsdf wrote:
Show nested quote +
On July 12 2009 05:37 coltrane wrote:
okok;


copypaste this and compile it:

#include <iostream>
using namespace std;

int main() {

int a;
double b;
char c;

cout << a << b << c;

return 0;

}


When you run that shit you will realize that:

Variables always have a value, even when you dont asign any variable to it.

So, a good manner thing is to put some value in a variable like the a in your program
WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing

double a;

for the sentence

double a(0);

^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable.


I will rewrite your code.

+ Show Spoiler +

#include <iostream>
using namespace std;

int main()
{
       double w, h;
       double a(0);
       cout << "Please enter your weight (in KG) and height (in meters)." << endl;
       cin >> w >> h;
       if (w <= 0 || h <= 0){
             cout << "Invalid input." << endl;
             //this line is a comment. The compiler will skip it. ok, you asked for
             //2 values, if they dont fit the condition then we end just here,
             // and a is 0 right now.
       } else {
             a = (w/(h*h));
             cout << "Your Body Mass Index is " << a << "." << endl;

             //a has a new valid value. And then we ask:

             if ( a > 0 && a < 20 )
             cout << "You have a low BMI." << endl;
             else if ( a > 20 && a < 25 )
             cout << "You are within the healthy BMI range. Congratulations!" << endl;
             else
             cout << "You have exceeded the healthy BMI range." << endl;
       // i suppose you understand why we dont need brackets {} in this if
       }
       // if the inputed values are useless to us, then we are here.
       return 0;
}



honestly I think that's overkill. As long as the programmer is smart enough to assign a value to the variable at some point before use (and hopefully a sanity check), there is no need to have every variable declaration include an assignment.

int a;
double b;
char c;

a = 0;
b = 0.0;
c = cin.get();

cout << a << b << c;

return 0;

There is no point declaring c with an initial value when you are just going to be getting it from the keyboard immediately after anyways.


yes, but is a good thing to understand that a variable will have some value always. Anyway i just said him to assign a value to a variable, not to every variable...
Jävla skit
Normal
Please log in or register to reply.
Live Events Refresh
Next event in 7h 44m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Nina 325
ProTech70
mouzHeroMarine 29
StarCraft: Brood War
Calm 7147
Sea 2012
EffOrt 722
Mini 428
Shuttle 389
BeSt 268
Stork 236
Snow 155
Light 105
Mind 86
[ Show more ]
Trikslyr68
Barracks 50
Hyun 42
Shinee 38
Rush 37
Pusan 33
Movie 30
Backho 21
scan(afreeca) 18
ajuk12(nOOB) 13
Shine 9
Dota 2
Gorgc10537
League of Legends
Dendi599
Counter-Strike
fl0m1064
Super Smash Bros
Mew2King146
Heroes of the Storm
Khaldor130
Other Games
hiko1270
Lowko395
Fuzer 239
Beastyqt203
ArmadaUGS85
QueenE57
ceh933
Organizations
StarCraft 2
angryscii 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• StrangeGG 84
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV584
• lizZardDota285
League of Legends
• Jankos1030
Other Games
• Shiphtur237
Upcoming Events
PiGosaur Monday
7h 44m
The PondCast
17h 44m
Replay Cast
1d 7h
RSL Revival
1d 17h
ByuN vs Classic
Clem vs Cham
WardiTV European League
1d 23h
Replay Cast
2 days
RSL Revival
2 days
herO vs SHIN
Reynor vs Cure
WardiTV European League
2 days
FEL
2 days
Korean StarCraft League
3 days
[ Show More ]
CranKy Ducklings
3 days
RSL Revival
3 days
FEL
3 days
Sparkling Tuna Cup
4 days
RSL Revival
4 days
FEL
4 days
BSL: ProLeague
5 days
Dewalt vs Bonyth
Replay Cast
6 days
Replay Cast
6 days
Liquipedia Results

Completed

Proleague 2025-06-28
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL 2v2 Season 3
BSL Season 20
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025
YaLLa Compass Qatar 2025

Upcoming

CSLPRO Last Chance 2025
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.