5 Replies - 551 Views - Last Post: 30 March 2013 - 02:04 AM Rate Topic: -----

#1 lewm  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 160
  • Joined: 29-March 13

c efficiency help

Posted 29 March 2013 - 12:37 PM

Hi im new to c programming less than 6 months, can I write this code more efficiently?
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

char player1name[100], player2name[100], playagain;
int num, gnum, playergo=1, p1score=0, p2score=0, lives=5;

main()
{
    mainscreen();
    getnames();
    do
    {
        mainscreen();
        numbertobeguessed();
        mainscreen();
        numberthatwasguessed();
        puts("\n\nPress enter to play again any other key quits...");
        playagain=getch();
    }while(playagain == '\r');
}

numberthatwasguessed()
{
    lives=5;
    if(playergo == 2)
    {
        printf("\n\n%s Go:\n\nTry and guess the number between 1 and 100:\n", player2name);
    }
    else
    {
        printf("\n\n%s Go:\n\nTry and guess the number between 1 and 100:\n", player1name);
    }
    do
    {
        printf("Lives %d\n", lives);
        gnum = getnumber();
        if(gnum > num)
        {
            puts("Too big.");
            lives--;
        }
        else
        if(gnum < num)
        {
            puts("Too small.");
            lives--;
        }
        else
        {
            puts("\n\nCongratulations.");
            if(playergo == 2)
                p2score++;
            if(playergo == 1)
                p1score++;
        }       
    }while(gnum != num && lives > 0);
    if(lives == 0)
        puts("\nSorry you have used all your lives.");
}

numbertobeguessed()
{
    if(playergo == 1)
    {
        printf("\n\n%s Go:\n\nPlease enter number between 1 and 100:\n", player1name);
        playergo = 2;
    }
    else
    {
        printf("\n\n%s Go:\n\nPlease enter number between 1 and 100:\n", player2name);
        playergo = 1;
    }
    num=getnumber();
}

int getnumber()
{
    char a[3];
    int i=0, result=0;
    
    do
    {
        i = 0;
        do
        {
            a[i]=getche();
            if(a[i] >= '0' && a[i] <= '9')
            {
                i++;
                if(i > 3)
                {
                    i = 0;
                    error();
                }
            }
            else
            if(a[i] != '\r')
            {
                i = 0;
                error();
            }
        }while(a[i] != '\r');
        a[i] = '\0';
        i=0;
        result = atoi(a);
        if(result > 100)
            error();
    }while(result > 100);
    return(result);    
}

error()
{
    puts("\nA NUMBER BETWEEN 1 AND 100 PLEASE");
}

getnames()
{
    puts("\n\nPlayer 1 please enter your name:");
    gets(player1name);
    puts("\nPlayer 2 please enter your name:");
    gets(player2name);
    mainscreen();
}

mainscreen()
{
    system("cls");
    printf("Programmed By Lewm\n\nGUESS THE NUMBER  Scores: %s %d   %s %d", player1name, p1score, player2name, p2score);
}


Is This A Good Question/Topic? 0
  • +

Replies To: c efficiency help

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9073
  • View blog
  • Posts: 34,115
  • Joined: 12-June 08

Re: c efficiency help

Posted 29 March 2013 - 12:41 PM

Mama mia! Why do you put 'c' code in the 'vb6' forum?

Moving.
Was This Post Helpful? 0
  • +
  • -

#3 lewm  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 160
  • Joined: 29-March 13

Re: c efficiency help

Posted 29 March 2013 - 01:04 PM

oops
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3548
  • View blog
  • Posts: 10,989
  • Joined: 05-May 12

Re: c efficiency help

Posted 29 March 2013 - 07:26 PM

Yes, it can be written more efficiently. You don't need to use any global variables, and you can write your functions so that you can have them to be more reusable. Notice how your getnumber() function is reusable because of its minimal need for globals. Your other functions can also be made as reusable. For example your numberthatwasguessed() can take the player name as a parameter, and it can return true if the player won. Based on the true value, your calling code can increment the appropriate player's score.

Another point of efficiency is using arrays and structures.

Here is some quick off the cuff pseudo code. I hope it gives you some ideas.
#define NumberOfPlayers 2
#define MaxGuesses 5

typedef struct
{
    char name[100];
    int score;
} Player;

int GetNextPlayer(int playerNumber, int maxPlayers)
{
    return (playerNumber + 1) % maxPlayers;
}

void GetPlayerName(int playerNumber, char name[], int maxLength)
{
    printf("Player %d, please enter your name: ", playerNumber);
    scanf("%s", name);
}

int PlayAgain()
{
    : // returns 1 if user indicates they want to play again.
}

int GetNumber()
{
    : // returns users input number
}

int GetNumberToBeGuessed(char * name)
{
    printf("%s, enter a number for the next player to guess: ", name);
    return GetNumber();
}

int SuccessfullyGuessedNumber(int goal, int maxGuesses, char * name)
{
    while (maxGuesses > 0)
    {
        printf("%s, enter your guess:", name);
        int guess = GetNumber();
        if (guess == goal)
            break;

        maxGuesses--;
        printf("You have %d guesses left.", maxGuesses);
    }
    return guess == goal;
}

int main()
{
    Player Scoreboard[NumberOfPlayers] = { 0 };

    for(int i = 0; i < NumberOfPlayers; i++)
        GetPlayerName(i + 1, Scoreboard[i].name, sizeof(Player.name));

    int currentPlayer = 0;
    do
    {
        int goal = GetNumberToBeGuessed(Scoreboard[currentPlayer].name);

        currentPlayer = GetNextPlayer(currentPlayer);
        
        if (SuccessfullyGuessedNumber(goal, MaxGuesses, Scoreboard[currentPlayer].name))
            Scoreboard[currentPlayer].score++;
    } while(!PlayAgain());
    return 0;
}


Was This Post Helpful? 0
  • +
  • -

#5 no2pencil  Icon User is online

  • Toubabo Koomi
  • member icon

Reputation: 5246
  • View blog
  • Posts: 27,062
  • Joined: 10-May 07

Re: c efficiency help

Posted 29 March 2013 - 07:29 PM

** Renamed title to be more specific **
Was This Post Helpful? 0
  • +
  • -

#6 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1643
  • View blog
  • Posts: 3,120
  • Joined: 30-May 10

Re: c efficiency help

Posted 30 March 2013 - 02:04 AM

Some notes on "efficiency", and how you need to be careful in what you're trying to optimise.

- the easiest code for someone else to maintain
- the easiest code to test for correctness
- the fastest code execution (meaningless since you have so much user I/O)
- the smallest memory footprint (in RAM)
- the smallest disk usage of the compiled code
- the smallest disk usage of the source code
- the quickest way to write the code from scratch

Some of these are mutually exclusive.
IOCCC quality entries may have the smallest source code, but they're far removed from being quick to write, easy to maintain etc.

Professional programmers care about 1 and 2 all the time, then care about 3 and 4 on an "as needed" basis when they've had a chance to run a profiler to find out where the real issues are in real code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1