Function

This is a discussion on Function within the C++ Programming forums, part of the General Programming Boards category; Guys, see that code: Code: int main () { int x; int resultado = 0; cout << "Coloque um numero ...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    17

    Function

    Guys, see that code:
    Code:
    int main ()
    {
    int x;
    int resultado = 0;
    cout << "Coloque um numero a ser fatorado e descubra se ele eh primo: " << endl <<"(Quanto maior o numero, mais demorado o cauculo.)" << endl;
    cin>>x;
    unsigned long int primo = x;
    while (primo>0){
    	if ((x%primo == 0) && (primo != x) && (primo != 1)){
    resultado = 1;
    cout << "Eh divisivel por " << primo << "    (" << x << " dividido por " << primo << " eh iguau a " << x/primo << ")" << endl;
    }
    primo = primo-1;
    }
    cin.get();
    if (resultado == 1)
    cout << "Logo, esta bunda nao eh primo!";
    else
    cout << "Ele eh primo! Viva Deus!";
      cin.get();
    }
    Well, i want to modify the program to do EXACTLY the same thing, but the factoration thing in a separated function.
    How do i do that? Thanks.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,340
    Take the code that you want to put into a separate function and move it outside main. Then put the opening and closing brace around the code. Then look for variables that you use within that code. For each variable, if it holds a value from outside the code you copied, then you must pass that value in as a parameter. If it does not use any value from outside the function code, then you can make it a local variable. If there are any values that are required back in main that are determined within the function code, then you have to return that value.

    Do this and play around with what code needs to be in the function and what needs to stay in main, and you'll get what you want.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21