facebook like button

Showing posts with label returning a structure. Show all posts
Showing posts with label returning a structure. Show all posts

10 January, 2012

Returning a structure in C

The need:
     This program is basically solution of a problem I found on internet. Problem statement is:
There is a purse filled with some coins of gold, silver ans copper. A person draws coins one by one and notes down the type of coin each time. He writes g for gold, s for silver and c for copper coin. Thus a character string is formed. You have to write a function countCoins() which takes that string as parameter and returns count each type of coin. As we know that a function can return only single value, we have 2 options left to return all three counts with one function:
    1. store 3 answers in some contiguous location and return a pointer to that location.
    2. If possible, club all three variables to make a single variable and return that single variable. Yes it is possible, we can make a structure variable containing all three counts and return that structure variable.

The code:
----------------------------------------------------------
#include<stdio.h>
typedef struct
{
    int silver;
    int copper;
    int gold;
}CoinPurse;
CoinPurse countCoin(char *);

int main()
{
    int i;
    CoinPurse a,*b;
    char *coins="gscgcc";
    a=countCoin(coins);
    printf("Coppper coins are %d\n",a.copper);
    printf("Gold coins are %d\n",a.gold);
    printf("Silver coins are %d\n",a.silver);
    return 0;
}

CoinPurse countCoin(char *coins)
{
    CoinPurse x;
    x.copper=0;
    x.gold=0;
    x.silver=0;
    while(*coins)
    {
        switch(*coins)
        {
        case 'c':    x.copper++;
                    break;
        case 'g':    x.gold++;
                    break;
        case 's':    x.silver++;
                    break;
        default:    break;
        }
        coins++;
    }
    return x;
}
----------------------------------------------------------
Approach:
    The approach is very simple. The structure CoinPurse contains counter for each type of coin. the function countCoin() takes a character string , examines each character and based on that increments the correct counter. after the string is finished, the structure containing the counts is returned by the function countCoin(). In this program i have given the character string *coins as "gscgcc" soit is clear that there are 2 gold, 1 silver and 3 copper coins which can be verified by the program output.