Thread: 3D Array - Printing Certain Rows in Order

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    27

    3D Array - Printing Certain Rows in Order

    Hey everyone,

    Currently, I'm working on a seven-segment display that is required to be in a 3D array. Here is the format I'm required to use:

    Code:
    const char segements[10][3][3] =
    { { {’ ’, ’_’, ’ ’}, {’|’, ’ ’, ’|’}, {’|’, ’_’, ’|’} }, ... };
    As a result, my current code is as follows:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void sevenSegmentDisplay(int userInput);
    const char segments[10][3][3] =
    {
        {{' ', '_', ' '}, {'|', ' ', '|'}, {'|', '_', '|'}}, //0
        {{' ', ' ', ' '}, {' ', ' ', '|'}, {' ', ' ', '|'}}, //1
        {{' ', '_', ' '}, {' ', '_', '|'}, {'|', '_', ' '}}, //2
        {{' ', '_', ' '}, {' ', '_', '|'}, {' ', '_', '|'}}, //3
        {{' ', ' ', ' '}, {'|', '_', '|'}, {' ', ' ', '|'}}, //4
        {{' ', '_', ' '}, {'|', '_', ' '}, {' ', '_', '|'}}, //5
        {{' ', '_', ' '}, {'|', '_', ' '}, {'|', '_', '|'}}, //6
        {{' ', '_', ' '}, {' ', ' ', '|'}, {' ', ' ', '|'}}, //7
        {{' ', '_', ' '}, {'|', '_', '|'}, {'|', '_', '|'}}, //8
        {{' ', '_', ' '}, {'|', '_', '|'}, {' ', '_', '|'}}, //9
    };
    
    
    int main(void)
    {
        int a;
        sevenSegmentDisplay(a);
        return 0;
    }
    
    
    void sevenSegmentDisplay(int userInput)
    {
        int i, j;
        printf("Please enter a number: ");
        userInput = getchar();
        if(userInput == '-')
        {
            // print a negative sign
        }
        while(userInput != '\n')
        {
            userInput = userInput - '0';
            for(i=0; i<3; i++)
            {
                for(j=0; j<3; j++)
                {
                    printf("%c", segments[userInput][i][j]);
                }
            putchar('\n');
            }
            userInput = getchar();
        }
    }
    Currently, my code will read in the user input and print each number individually, with newlines in between each one.

    i.e.

    Code:
     |
     |
    
     _ 
    | |
    |_|
    I'm currently stumped on how to properly increment the variables in my array to print the numbers together, on one line.

    i.e.

    Code:
     _  
    | |  |
    |_|  |
    imo, the logical thing would be to implement strings, but we have not covered that yet. I'm currently just supposed to use float, char, and int.

    Thanks in advance. I'll be working on this in the meantime, will update if I stumble upon anything.
    Last edited by kapkong; 02-20-2017 at 02:19 PM.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    You'll need read in the entire number and then print the top row of all of them, then the next row, then the last row.

    BTW, you could define your numbers like this (which looks a lot nicer! ) :
    Code:
    const char segments[10][3][3] =
    {
        {" _ ",
         "| |",
         "|_|"},
        {"   ",
         "  |",
         "  |"},
        {" _ ",
         " _|",
         "|_ "},
        ...
    };

  3. #3
    Registered User
    Join Date
    Feb 2017
    Posts
    27

    Change in Array Format

    Hey algorism,

    I've been struggling with implementation for the past couple of hours; having done a bit more research on the subject, I'm trying a change in my array structure:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    const char segments[3][10][3] =
    {
       {" _ ", "   ", " _ ", " _ ", "   ", " _ ", " _ ", " _ ", " _ ", " _ "},
       {"| |", "  |", " _|", " _|", "|_|", "|_ ", "|_ ", "  |", "|_|", "|_|"},
       {"|_|", "  |", "|_ ", " _|", "  |", " _|", "|_|", "  |", "|_|", "  |"},
    };
    
    
    int main(void)
    {
        int i, j, k;
        for(i=0; i<3;i++){
            printf("%s", segments[i][2]);
        }
        return 0;
    }
    I'm fine with using strings for this, but my current output is not what I want ('2' in seven-segment). I get a bunch of gibberish with random %s included.

    Sorry for the hassle, I've been struggling over this for the past while and am unsure what the issue is with my loop / array.

    Thanks!

    EDIT: FML. Figured that it's because I forgot about the NULL terminator, which means I have to increase the 3rd d of my array. Sorry
    Last edited by kapkong; 02-20-2017 at 05:59 PM.

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I like the change in structure.

    Interestingly, C allows a special case of initializing a char array from a string literal while leaving off the zero-terminator. E.g., char a[4] = "1234" leaves off the terminator but doesn't cause a warning even though "1234" actually has 5 chars. But you couldn't do char a[3] = "1234" without a warning, for example.

    BTW, it can be shrunk even more. "%.3s" only prints the first 3 chars.
    Code:
    #include <stdio.h>
    
    const char seg[3][30] = {
      {" _     _  _     _  _  _  _  _ "},
      {"| |  | _| _||_||_ |_   ||_||_|"},
      {"|_|  ||_  _|  | _||_|  ||_|  |"}
    };
    
    int main() {
        int row, dig = 2;
        for (row = 0; row < 3; row++)
            printf("%.3s\n", seg[row] + dig * 3);
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Feb 2017
    Posts
    27

    Implementing Negatives

    @algorism Yeah, that 2D array looks much cleaner and easier to iterate through, but unfortunately my array being 3D is a requirement.

    So here's where my code stands. As it is, it is fully functional, except for one thing:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    void seven_segment();
    const char segments[3][11][4] =
    {
       {" _ ", "   ", " _ ", " _ ", "   ", " _ ", " _ ", " _ ", " _ ", " _ ", "   "},
       {"| |", "  |", " _|", " _|", "|_|", "|_ ", "|_ ", "  |", "|_|", "|_|", " _ "},
       {"|_|", "  |", "|_ ", " _|", "  |", " _|", "|_|", "  |", "|_|", "  |", "   "},
    };
    
    
    int main(void)
    {
        char YorN;
        for(;;)
        {
            seven_segment();
            printf("Please enter Y or N if you wish to continue or exit, respectively: ");
            scanf(" %c", &YorN);
            if(YorN == 'Y' | YorN == 'y')
                continue;
            else if(YorN == 'N' | YorN == 'n')
            {
                printf("Thanks for using my program!");
                exit(0);
            }
            else
            {
                while(YorN != 'Y' && YorN != 'N' && YorN != 'y' && YorN != 'n')
                {
                    printf("Sorry, that was not a valid input.  Please enter Y or N: ");
                    scanf(" %1c", &YorN);
                    if(YorN == 'N' | YorN == 'n')
                    {
                        printf("Thanks for using my program!");
                        exit(0);
                    }
                }
                continue;
            }
        }
        return 0;
    }
    
    
    void seven_segment()
    {
        int userInput, i, j;
    
    
        printf("Please enter a number to display: ");
        scanf("%d", &userInput);
    
    
        char intLength[25];
        sprintf(intLength, "%d", userInput);
    
    
        for(i=0; i<3; i++)
        {
            for(j=0; j<strlen(intLength); j++)
            {
                printf("%s ", segments[i][intLength[j]-'0']);
            }
            putchar('\n');
        }
    }
    How would I best implement adding a negative sign in front of negative integers?

    I've added in an extra column for the negative sign, but am unsure how to iterate to it through my nested for loop correctly.

    My previous attempt looked like this:

    Code:
    if(j = 0 && userInput < 0)
    printf("%s ", segments[i][11]);
    But this yielded an infinite loop.

    Sorry for the confusion, and thanks again for any advice!

  6. #6
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Firstly, remember that the index of your negative sign is 10, not 11.

    I would make the interface for seven_segment take an int (or a long (or long long)), read the number in main and pass it in. That seems more natural to me.

    For the negative sign, maybe something like this:
    Code:
    #define BASE 10
    #define ROWS  3
      
    void seven_segment(long n);
    
    const char segments[ROWS][BASE+1][4] =
    {
      {" _ ","   "," _ "," _ ","   "," _ "," _ "," _ "," _ "," _ ","  "},
      {"| |","  |"," _|"," _|","|_|","|_ ","|_ ","  |","|_|","|_|"," _"},
      {"|_|","  |","|_ "," _|","  |"," _|","|_|","  |","|_|","  |","  "}
    };
    
    // main ...
    
    void seven_segment(long n) {
        int row, digit;
        char str[32];
        int len = sprintf(str, "%ld", n);
    
        for (row = 0; row < ROWS; row++) {
            for (digit = 0; digit < len; digit++) {
                int value = str[digit] == '-' ? BASE : str[digit] - '0';
                printf("%s ", segments[row][value]);
            }
            putchar('\n');
        }
    }
    Also, I removed the space to the right of the negative sign picture (in the segments array) so that it was a little closer to the first digit. You might not want to do that.

  7. #7
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    You have three times the wrong OR-operator in your code.
    Quote Originally Posted by kapkong View Post
    Code:
    …
            if(YorN == 'Y' | YorN == 'y')
    …
    This line should be:
    Code:
    …
            if(YorN == 'Y' || YorN == 'y')
    …
    | = bitwise OR
    || = boolian OR
    Other have classes, we are class

  8. #8
    Registered User
    Join Date
    Feb 2017
    Posts
    27

    Thanks again! (and sorry for the delay)

    Hey everyone, thanks again for the help.

    @WoodSTokk- Thanks for catching this typo. Certainly a sign of my inexperience I appreciate it.

    @algorism - That makes so much sense! You also taught me about the ?: operator I didn't use it here for the sake of simplicity's sake (and the fact we haven't learnt it) but will certainly try to do so in my future C endeavours.

    Implementing a separate int makes it so much easier. Here's where my code currently stands (functional atm):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define DIGITS 10
    
    
    void seven_segment();
    const char segments[3][DIGITS + 1][4] =
    {
       {" _ ", "   ", " _ ", " _ ", "   ", " _ ", " _ ", " _ ", " _ ", " _ ", "   "},
       {"| |", "  |", " _|", " _|", "|_|", "|_ ", "|_ ", "  |", "|_|", "|_|", " __"},
       {"|_|", "  |", "|_ ", " _|", "  |", " _|", "|_|", "  |", "|_|", "  |", "   "},
    };
    
    
    int main(void)
    {
        char YorN;
        for(;;)
        {
            seven_segment();
            printf("Please enter Y or N if you wish to continue or exit, respectively: ");
            scanf(" %c", &YorN);
            if(YorN == 'Y' || YorN == 'y')
                continue;
            else if(YorN == 'N' || YorN == 'n')
            {
                printf("Thanks for using my program!");
                exit(0);
            }
            else
            {
                while(YorN != 'Y' && YorN != 'N' && YorN != 'y' && YorN != 'n')
                {
                    printf("Sorry, that was not a valid input.  Please enter Y or N: ");
                    scanf(" %1c", &YorN);
                    if(YorN == 'N' || YorN == 'n')
                    {
                        printf("Thanks for using my program!");
                        exit(0);
                    }
                }
                continue;
            }
        }
        return 0;
    }
    
    
    void seven_segment()
    {
        int userInput, i, j;
    
    
        printf("Please enter a number to display: ");
        scanf("%d", &userInput);
    
    
        char intLength[25];
        sprintf(intLength, "%d", userInput);
    
    
        for(i=0; i<3; i++)
        {
            for(j=0; j<strlen(intLength); j++)
            {
                int number = intLength[j];
                if(number == '-')
                    number = DIGITS;
                else
                    number = intLength[j] - '0';
                printf("%s ", segments[i][number]);
            }
            putchar('\n');
        }
    }

  9. #9
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Your main is a little overly-complicated. Maybe something like this (not perfect, but better) :
    Code:
    int main(void) {
        char answer;
        int c;
    
        for(;;) {
            seven_segment();
    
            for (;;) {
                printf("Do you want to do another number (Y/N)?: ");
                scanf(" %c", &answer);
    
                if (answer == 'N' || answer == 'n') {
                    printf("Thanks for using my program!\n");
                    exit(0);
                }
    
                // eat newline (and any extra characters)
                while ((c = getchar()) != '\n')
                    ;
    
                if (answer == 'Y' || answer == 'y')
                    break;
    
                printf("That was not a valid input. Try again.\n");
            }
        }
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-02-2011, 04:28 PM
  2. Help printing array in ascending order in C programming?
    By celticpride in forum C Programming
    Replies: 5
    Last Post: 04-06-2011, 03:19 PM
  3. Printing an array in reverse order!
    By jaja009 in forum C Programming
    Replies: 3
    Last Post: 03-04-2010, 11:04 PM
  4. printing array elements in ascending order
    By galmca in forum C Programming
    Replies: 29
    Last Post: 10-24-2004, 11:24 PM
  5. printing rows and columns
    By datainjector in forum C# Programming
    Replies: 1
    Last Post: 08-03-2003, 05:42 PM

Tags for this Thread