Programming in C question. Printing Arrays

In summary: Using the modulo operator would definitely make the code more concise and readable. Thank you for sharing your solution. In summary, the conversation discusses a programming problem where the user needs to create an array and print it in different ways. The solution involves using nested for loops or an if statement with modulo to print the array in the desired format. The conversation also mentions the importance of using proper programming practices such as including braces for loop bodies.
  • #1
Vagabond7
50
11

Homework Statement


Alright, I actually solved this problem myself, it is just ugly and hilariously inelegant. I won't lose points since it is an introductory course, and it technically works, but I wondered what the "right way" to do this is.

Here is what I had to do. Create an array where the user inputs 20 values to go into the array. Then print the array with 5 numbers per line in order the user input it. Then print it 4x4 in reverse order.

I did this, but it is hilariously bad. Like I said, my teacher only cares if it works, but for the sake of learning things correctly I would like to know to proper way to do this.


Homework Equations





The Attempt at a Solution



Code:
#include <stdio.h>
int main ()
{int i = 0;
    int A[20];//Array creation
  for ( i = 0; i < 20; i++ ) {
      printf("Enter a value: ");
    scanf("%d", &A[i]); // entering numbers into the array
   } /* end for */
 
for ( i = 0; i < 5; ++i ) // The part the prints the array in order with 5 numbers per row
    printf ("%d", A[i]);
    printf ("\n");
for ( i = 5; i < 10; ++i )
    printf ("%d", A[i]);
    printf ("\n");
for ( i = 10; i < 15; ++i )
    printf ("%d", A[i]); 
    printf ("\n");
for ( i = 15; i < 20; ++i )
    printf ("%d", A[i]); 
    printf ("\n\n\n\n");// making space for aesthetic reasons

for ( i = 19; i > 15; --i )// The hilarious solution to printing the array backwards, the punchline is really good.
    printf ("%d", A[i]); 
    printf ("\n");
for ( i = 15; i > 11; --i )
    printf ("%d", A[i]); 
    printf ("\n");   
for ( i = 11; i > 7; --i )
    printf ("%d", A[i]); 
    printf ("\n");   
 for ( i = 7; i > 3; --i )
    printf ("%d", A[i]); 
    printf ("\n"); 
 for ( i = 3; i > 0; --i )
    printf ("%d", A[i]);  
    printf ("%d", A[0]);
    
    getch ();
    return 0;
} //program ending


I especially find the part where I just slap on print A[0] because the counter wasn't counting down all the way to A[0]. I know it's rough, but it works. What is a better way to do this?
 
Physics news on Phys.org
  • #2
You need to use nested for loops to do what you want. For the first part, where you print 4 lines, with 5 numbers per line, you could do this:
Code:
for (i = 0; i < 4; i++)
{
   for (j = 0; j < 5; j++)
   {
      printf("%d ", A[4*i + j]);
   }
   printf("\n");
}

Think about how this works. The outer loop runs slower than the inner loop in that each iteration of the outer loop has 5 iterations of the inner loop.

When i is 0, j take on values 0, 1, 2, 3, and 4, and you print A[0], A[1], A[2], A[3], and A[4], then you print a new-line character.

When i is 1, j takes on the same values as above, and you print A[4*1 + 0], A[4*1 +1], A[4*1 +2], A[4*1 +3], and A[4*1 +4], then you print a new-line character.

And so on.

You can do the same sort of thing to print out the array values in reverse, with 5 lines of 4 values per line (you said 4 X 4) but I think this is what you meant).

It's bad programming practice to neglect putting in braces for your for loops (and other loops and if blocks). When you write things like this:

Code:
for ( i = 3; i > 0; --i )
    printf ("%d", A[i]);  
    printf ("%d", A[0]);
    getch ();
    return 0;

your indentation suggests that there are four statements in the loop body, but there is only one. You might understand that there is only one statement in the loop body, but someone who is maintaining your code will mistakenly think that all four statements are in the loop body.

A better way to write this is like so:
Code:
for ( i = 3; i > 0; --i )
{
    printf ("%d", A[i]);
}  
printf ("%d", A[0]);
getch ();
return 0;
 
Last edited:
  • #3
In addition to using nested loops, you could use an if with modulo.

Code:
    for(i = 0; i < 20; ++i){
        printf("%d ", A[i]);
        if((i%5) == 4){
            printf("\n");
        }
    }
 
  • #4
rcgldr said:
In addition to using nested loops, you could use an if with modulo.

Code:
    for(i = 0; i < 20; ++i){
        printf("%d ", A[i]);
        if((i%5) == 4){
            printf("\n");
        }
    }

Nice!
 
  • #5



I understand the need for efficient and elegant solutions in programming. In this case, a more efficient way to print the array would be to use nested for loops. The first loop would iterate through the rows and the second loop would iterate through the columns, each time printing the value at the current index of the array. This would eliminate the need for multiple printf statements and make the code more readable and maintainable.

Additionally, to print the array in reverse order, you could use a single for loop that starts at the last index of the array and iterates backwards, printing the values at each index. This would eliminate the need for multiple printf statements and simplify the code.

In general, it is important to consider the efficiency and readability of your code when programming. As you continue to learn and improve your skills, I encourage you to explore different methods and techniques to optimize your code and make it more elegant.
 

Related to Programming in C question. Printing Arrays

1. What is an array in C?

An array in C is a data structure that allows you to store a collection of elements of the same data type in a contiguous block of memory. Each element in the array can be accessed using its index, which starts from 0.

2. How do you declare and initialize an array in C?

To declare an array in C, you use the following syntax: data_type array_name[array_size]; To initialize the array, you can either specify the values inside curly braces {} or use a for loop to assign values to each element.

3. How do you print an array in C?

To print an array in C, you can use a for loop to iterate through each element and print it using the printf() function. Alternatively, you can also use the puts() function to print each element on a new line.

4. Can you change the size of an array in C?

No, the size of an array in C is fixed at the time of declaration and cannot be changed. If you need to store more elements, you will have to declare a new array with a larger size and copy the elements from the old array.

5. What is the difference between an array and a pointer in C?

An array and a pointer may seem similar, but they are different data types in C. An array is a collection of elements that are stored in a contiguous block of memory, while a pointer is a variable that stores the memory address of another variable. Arrays can be accessed using their indices, while pointers are dereferenced to access the value they are pointing to.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
862
  • Engineering and Comp Sci Homework Help
Replies
3
Views
992
  • Engineering and Comp Sci Homework Help
Replies
3
Views
783
  • Engineering and Comp Sci Homework Help
Replies
4
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
9K
Back
Top