First post here. I'm new to C++ but I am picking up things rather quickly. I wrote a program to compute the squares of integers and I'm faced with the following dilemma:
Program #1
-----------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Program to demonstrate use of for loops
#include<iostream>
usingnamespace std;
int main()
{
int i,j;
for(i=1;i<=10;i++)
{
j=i*i;
cout<<"The value of i is: "<< i << "\n";
cout<<"The value of j=i^2 is:"<<j<<"\n";
}
return 0;
}
The output is what is expected, i.e squares of the integers from 1 to 10.
Now, when I change j=i^2 instead of i*i on line 11, I get the following output:
3,0,1,6,7,11,8
Random numbers. What is going on? Why does writing i^2 mess things up?
I would like to UNDERSTAND the discrepancy and would definitely put in the time to read up on any hints you may suggest.
PS#
----
I saw a thread where somebody complained about the console disappearing quickly in the VC++ IDE. The solution is very simple. Create your project as a Win32 console application. This is what I do in VC++ 2010:
Ctrl+Shift+N ->Win32Console App->Uncheck pre-compiled headers->Select Empty Project.
Alt+F7->Config Properties->General->CharacterSet (change from unicode to Not Set).
^ is not an exponent operator in C++. It's a bitwise XOR operator.
By doing j = i ^ 2; you're effectively "toggling" the '2' bit (basically either adding or subtracting 2, depending on whether or not that bit is set).
C++ has no exponent operator. i * i is the correct way to square something. For more complicated exponent operations, there's a pow() function in the cmath header, but don't use it unless you really need it. It's overkill for simple squaring.
Thank you for the clarification. I am used to MATLAB programming, so this is something very new to me!
On a related note, I was trying another program to print A-Z which looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Program using characters in loops. This program prints out the alphabet.
#include<iostream>
usingnamespace std;
int main()
{
char letter;
for(letter='A';letter<='Z';letter++) // Using letter<='number' crashes the computer!
{
cout<<letter;
// cout<<"\n";
}
return 0;
}
When I try to use letter='100' (just to see what happens), the console output is gibberish, there is a persistent beep and the console process cannot be killed via Taskmanager (even if VC++ 2010 is killed). The only option is to restart the computer. What just happened? Why did everything blow up?
'100' is too big to fit in a single char. It actually is 3 chars ('1', '0', and '0'). Therefore your loop condition is never met (letter will always be <= '100', therefore you have an infinite loop).
The beeping is caused because there's a "beep" character that's plays a beep when you print it. It has a low value that 'letter' would be cycling through repeatedly, so you would keep playing the beep over and over.
As for why VS or Task Manager couldn't kill it. I don't know. They should've been able to.