I need help1

Why my program doesn't work?It is suppose to ask me for a number and square it for me but its not working
Thank you for reading this

#include <conio.h>
#include <iostream>

int square(int x)
{
int result;

result=x*x;

return result;
}

int main(int argc, char *argv[])
{
int a;
int x;
printf("what are you waiting for enter your number\n");
scanf("%d",&a);
x=square(a);

getch();
return EXIT_SUCCESS;
}
Your program seems to work, you just don't have an output statement yet to print the results of the squared number to the screen.

<conio.h> is an old header file - I had to update to #include <cstdio> to compile this.
Thanks wild blue
I added
printf("The value of result is %d",x);
to body of main function and it works fine now

God bless you
closed account (z1CpDjzh)
FIRST:
You should not be using printf() and scanf() in c++... those are c functions and you should instead use cout and cin... because they are more secure.

SECOND:
In function square why did you make a new variable... you could just put return x*x;

THIRD:
before the return you put getch... why? did you want to pause the program... but for what... cin pauses for input.... or did you want the user to see the results... because there is nothing to print it out.
Anyway getch like printf and scanf is from c and the safer more reliable c++ version is cin... you could put cin.get to replace it.

Fourth:

return EXIT_SUCCESS;????We want a int... and you could just put 0 which usually means success.... or did you put a #define EXIT_SUCCESS 0 in the code?
Finally your code should look like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include <conio.h>
#include <iostream>       

int square(int x)
{
return x*x;
}

int main(int argc, char *argv[])
{
int a;
int x;
std::cout << "what are you waiting for, just enter your number\n";
std::cin >> a;
x=square(a);
std::cout << x << "\n";
std::cin.ignore();//Ignores previous input, get cin.get working even with new line inputs.
std::cin.get();
return 0;
}

PS: Your code did work.... but did not pause or print out the output... also in the cmath header there is a sqrt() function which would work very well in this situation.
Last edited on
Wow what a reply
Thanks a lot TheGentlmen
Topic archived. No new replies allowed.