-2

I am new to the C Programming language and I am learning about functions. I decided to write a simple program to square a number using functions. I get the desired output, however I would like to know if I have implemented it correctly?

To be more precise, how can this code be improved?

#include <stdio.h>
#include <cs50.h>

int square(int x);

int number;

int main(void)
{
   printf("Which number would you like to square? ");
   number = get_int();
   printf("The square of %i is %i\n", number, square(number));
   return 0;
}

int square(int x)
{
  for (int i = 1; i <= number; i++)
  {
     number = x * x;
  }
  return number;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

2 Answers2

1

Global variables are bad! Bad bad bad! In fact, some languages don't allow them at all. Let's reduce the scope of number as much as possible:

int main(void) {
    printf("Which number would you like to square? ");
    int number = get_int();
    printf("The square of %i is %i\n", number, square(number));
    return 0;
}

Now, let's fix your square function:

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

It's just like how you'd square a number on a calculator.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • May I know the reason why global variables are so bad? Why do they even exist in C? –  Jul 29 '18 at 13:14
  • ["The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables."](https://stackoverflow.com/a/485020) That is: readability; contractual guarantees (you can control and guarantee *who* is allowed to modify a variable); increased locality; fewer things to keep track of and worry about when debugging or reading code. – Mateen Ulhaq Jul 29 '18 at 13:53
  • Why do they exist? In those days (1972), people were still figuring out how to design good programs. (And they still are!) Also, C is very close to assembly/machine code which have no concept of scope. These days, many programming languages also have global variables but the consensus is to not use them. – Mateen Ulhaq Jul 29 '18 at 13:55
  • @AlokY: Globals exist because there are specific cases where they are the right answer. In general, however, they should be avoided because they can create large-scale maintenance headaches. *Ideally*, functions should only communicate through parameters, return values, and exceptions (where applicable). – John Bode Aug 02 '18 at 15:10
0

You used a global variable number in your code!these variables remain in memory even after we're done with them and this makes lots of complications and unnecessary use of memory

You can write your square function like:

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

However, it's also better to write your code to make the most use of it!what if later you need to calculate Cube of that number?so try to write power function or even try it recursively!

I'mDoneOK
  • 39
  • 2
  • 9