https://cs50.harvard.edu/x/2023/sections/2/
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main (void)
{
string name = get_string("Type here: ");
int length = strlen(name);
int count = 0;
for (int i = 0; i < length; i++)
{
if(i != 0)
{
if(name[i] < name[i-1])
{
count++;
}
}
}
if(count == 0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
위가 작성한 답안. count를 사용했다.
아래가 제시된 답안.
bool을 사용해서 아래처럼 하는게 좀더 직관적으로 보인다.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
// Get input from the user
string word = get_string("Word: ");
// Determine length of our string
int length = strlen(word);
// First, assume everything is alphabetical
bool alphabetical = true;
// Look at every character
for (int i = 1; i < length; i++)
{
// If a character is not alphabetical from the one previous
if (word[i] < word[i - 1])
{
alphabetical = false;
}
}
if (alphabetical)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}