Thread: Display Indices in For Loop

  1. #1
    Registered User Mcdom34's Avatar
    Join Date
    Jun 2012
    North Royalton, Ohio, United States

    Display Indices in For Loop

    I'm writing a program that will display 70 random temperatures, using an array that stores each number. They are going to be divided into weeks (7 temperatThe loures per line), and before displaying each of the seven temperatures, I want to first display the week #. The loops I'm using work, however the variable 'i' always first displays 2, and then counts. The loop initializes it to 0, so I don't know why it's immediately obtaining a value of two. The code is posted below.
    static void DisplayTemps(int[] a)
                Console.WriteLine("Su M  T  W  Th F  S"); 
                for (int i = 0; i < a.Length / 7; i++)
                    Console.Write("Week {0}    ", i); 
                    for (int j=(i * 7); j < a.Length; j++)
                        if ((j + 1) % 7 == 0 && j != 0)
                            Console.Write("{0} ", a[j]);

  2. #2
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Why not use List<Temperatures> where Temperatures is a collection of 7 temperatures..1 for each day of the week? C# has much better constructs for this than primitive arrays.

    public class Temperatures
        public int Sunday { get; set; }
        public int Monday { get; set; }
        public int Tuesday { get; set; }
        public int Wednesday { get; set; }
        public int Thursday { get; set; }
        public int Friday { get; set; }
        public int Saturday { get; get; }
    List<Temperatures> temperatureCollection = new List<Temperatures>();
    Otherwise if you must use an array you should check that the array length is a multiple of 7. If it is not your code will crash. You should be able to do all of this with 1 for loop and 1 line of code within the loop. Why are you printing the temps 1 at a time? Why do you have two for loops? Unroll the inner loop and you simplify the code.
    Last edited by VirtualAce; 06-28-2012 at 05:27 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 09-23-2011, 04:07 PM
  2. XNA 3d - 32 bit indices
    By musicman in forum Game Programming
    Replies: 1
    Last Post: 09-06-2011, 10:15 PM
  3. Vertices and Indices
    By beene in forum Game Programming
    Replies: 15
    Last Post: 05-07-2007, 03:08 AM
  4. Array of indices
    By ronenk in forum C Programming
    Replies: 4
    Last Post: 06-15-2004, 05:36 PM
  5. What does 'indices' mean?
    By Shadow12345 in forum C++ Programming
    Replies: 1
    Last Post: 11-15-2002, 07:54 AM