Home > Enterprise >  Two for loops only one is showing
Two for loops only one is showing

Time:04-04

This program is not recognizing the second for loop. It stops after printing the length. Looking for this result: 41WH( Size of Array: 5 4 - Yes, this is a number 1 - Yes, this is a number W - Yes, this is an alphabet. H - Yes, this is an alphabet. ( - No, this is not a number or alphabet

#include <stdio.h>

int main()
{
    char misc[5];

    misc[0] = '4';
    misc[1] = '1';
    misc[2] = 'W';
    misc[3] = 'H';
    misc[4] = '(';
    misc[5] = '\0';

    size_t length = sizeof(misc)/sizeof(misc[0]);

    for(int a; a < length; a  )
    {
        printf("%c", misc[a]);
    }

    printf("\nSize of Array: %d\n", length);

    for(int i; i<length; i  )
    {
        if (misc[i] >= '0' && misc[i] <= '9')
        {
            printf("%c - ", misc[i]);
            printf("Yes, this is a number\n");
        }
        else if ((misc[i] >= 'a' && misc[i] <= 'z') || (misc[i] >= 'A' && misc[i] <= 'Z'))
        {
            printf("%c - Yes, this is an alphabet.\n", misc[i]);
        }
        else
        {
            printf("%c - ", misc[i]);
            printf("No, this is not a number or alphabet\n");
        }
    }
    return 0;
}

CodePudding user response:

Your code has undefined behaviour. That is practically the end of the explanation.

  • (as pointed out by Cediwelli) you access beyond the highest legal index 4 of the array misc
  • you are using i without ever initialising it

CodePudding user response:

You had one out of bounds error (off-by-one) for the length of the Array. Also you did not initilize the int a with 0. The code below works for me.

#include <stdio.h>

int main()
{
    size_t length = 6;
    char misc[length]; // 6 not 5

    misc[0] = '4';
    misc[1] = '1';
    misc[2] = 'W';
    misc[3] = 'H';
    misc[4] = '(';
    misc[5] = '\0'; // not out of bounds anymore

    for(int a = 0; a < length; a  ) // Initilize with 0 here
    {
        printf("%c", misc[a]);
    }

    printf("\nSize of Array: %d\n", length);

    for(int i = 0; i<length; i  ) // Initilize with 0 here, too
    {
        if (misc[i] >= '0' && misc[i] <= '9')
        {
            printf("%c - ", misc[i]);
            printf("Yes, this is a number\n");
        }
        else if ((misc[i] >= 'a' && misc[i] <= 'z') || (misc[i] >= 'A' && misc[i] <= 'Z'))
        {
            printf("%c - Yes, this is an alphabet.\n", misc[i]);
        }
        else
        {
            printf("%c - ", misc[i]);
            printf("No, this is not a number or alphabet\n");
        }
    }
    return 0;
}
  •  Tags:  
  • c
  • Related