Search code examples
arraysstringwhile-loopputs

Basic explanation needed while using while loops and arrays


// ConsoleApplication27.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include "stdio.h"  
#include <string.h>

void main()
{
char couples[5][50] = { "John Nora", "Paul Kathy", "Tom Claire", "Martin Mary", "Tony Teresa" };
char male[5][51];
char female[5][51];
int i;
int j = 0;

printf("Males: ");
for (i = 0; i < 5; i++)
{
    while (couples[i][j] != ' ')
    {
        male[i][j] = couples[i][j];
        j++;
    }
    male[i][j] = '\0';
    puts(male[i]);
    j = 0;
}       
printf("\n");


}

Hello, I am essentially trying to print all the male names and then print the female names (I have yet to do that part). The code below does work however I'm just finding it difficult to understand how it is working. Like, for example I don't understand the part where it says while(couples[I][j] != ' '). If I am trying to split the string by the space mark, why is it NOT equal to space. I would appreciate any sort of help and explanation people may have! Thanks!


Solution

  • Each row of 'couples' can be treated as a string (i.e a character array) consisting of two names - one male, one female - separated by a single space character. The 'while' loop is copying the male name of the pair into the separate array 'male', one character at a time. The intended action of the 'while' loop is to keep copying characters until the separating space is encountered, then put in the '\0' to mark the end of the copied male name-string. But 'while' means 'do this as long as some condition is true', so the condition you want to be true is that the space ISN'T the character being looked at right now. Execute the code in your head on the first row of 'couples', like so:

    a) i=0 and j=0 and enter the 'while' loop:
    b) couples[i][j] = 'J'.  Is 'J' != ' ' ? --> YES, copy 'J' to males[0][0], increment j
    c) couples[i][j] = 'o'.  Is 'o' != ' ' ? --> YES, copy 'o' to males[0][1], increment j
    d) couples[i][j] = 'h'.  Is 'h' != ' ' ? --> YES, copy 'h' to males[0][2], increment j
    e) couples[i][j] = 'n'.  Is 'n' != ' ' ? --> YES, copy 'n' to males[0][3], increment j
    f) couples[i][j] = ' '.  Is ' ' != ' ' ? --> NO, copy '\0' to males[0][4], reset j to 0