Thursday, September 20, 2012

Initializing Structures and Array of Structures Part I

What is interesting here is the use of constants. Why is good to use constants? Well is gonna provide you with more efficient code. If you use a constant you can easily change  the size of your array, you just assign a new value to your constant instead of changing one by one the size of the arrays. Use of constants = better code.
How to use a constant? constant THECONSTANTNAME = a value;
The name of a constant is all capitals by convention. Just in case, I think you provably know it, you gotta put the word constant before the constant name ;)
  •  Write a declaration for a variable salesAnnual of type Money (a structured type with two int fields, dollars and cents) and initialize it to represent $1,325,023.47.


struct Money{
int dollars, cents;};
Money salesAnnual;
salesAnnual.dollars = 1325023;
salesAnnual.cents = 47;


  •  Write a declaration for these variables: salesQuarter1, salesQuarter2, salesQuarter3, and salesQuarter4, all of type Money (a structured type with two int fields, dollars and cents) and initialize these variables to $350,249.22, $381,100.00, $291,527.06, and $142,447.38 respectively.


struct Money{
int dollars, cents;};
Money salesQuarter1;
Money salesQuarter2;
Money salesQuarter3;
Money salesQuarter4;
salesQuarter1.dollars=350249;
salesQuarter1.cents = 22;
salesQuarter2.dollars=381100;
salesQuarter2.cents = 0;
salesQuarter3.dollars=291527;
salesQuarter3.cents = 6;
salesQuarter4.dollars=142447;
salesQuarter4.cents = 38;



  •  Given a type Money that is a structured type with two int fields, dollars and cents declare an array monthlySales with 12 elements of type Money.

Money monthlySales[12];

  •  Assume a structured type, PrecinctReport, with these fields, address (a string), felonies, murders, and robberies. Declare an array named allPrecincts with NPRECINCTS elements, each of type PrecinctReport. (NPRECINCTS is a pre-declared constant.)
PrecinctReport allPrecincts[NPRECINCTS];




3 comments:

  1. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  2. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  3. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete