Thread: 2d arrays

  1. #1
    Registered User
    Join Date
    Jun 2011

    2d arrays

    how to print a specific number in the array? Like for my program I have to calculate the cost of 5 companies in 4 years. For the last function how do I let say print the total cost of company 1.

    #include <stdio.h>
    void getvalues();
    double totalcost(float);
    void main()
        y=double totalcost(cost);
    void getvalues()
    	float cost[5][6];
    	int i,y,com=0,year=0;
    		printf("Please enter the electricity cost for Company %d, year %d:",com,year);
    	double totalcost(float c)
    	int selection;
    	printf("Please enter the number of company");

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    You need to figure out who "owns" your data. Currently the getvalues function owns your cost data, which means that it is fruitless for any other function (like main, or totalcost) to even attempt to dream about the data, let alone use it in a meaningful way.

    It is typical for your data to be "owned" by the main program, which passes it to functions as necessary for them to operate on. So you should put your array in main, pass it to getvalues to be filled in, and then pass it to totalcost to be calculated with.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Use variables that make sense, and you will have your answer:
    float costs[ 5 ][ 6 ];
    int cost, company;
    printf( "Which company (0-4)?\n" );
    scanf( "%d", &company )
    if( company > -1 && company < COMPANIES )
        for( cost = 0; cost < COSTS; cost++ )
            dosomething( costs[ company ][ cost ] );
    Now it doesn't actually matter if you treat "rows" as the company, or the "columns" as the company. You can do whatever you want. Just stick with whatever you choose throughout your program and don't flip-flop back and forth.

    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  2. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  3. Replies: 2
    Last Post: 02-23-2004, 06:34 AM
  4. Parallel Arrays with Multiple Arrays
    By Billye Scott in forum C++ Programming
    Replies: 0
    Last Post: 03-02-2002, 11:14 PM
  5. separating line of arrays into array of arrays
    By robocop in forum C++ Programming
    Replies: 3
    Last Post: 10-20-2001, 12:43 AM