https://cs50.harvard.edu/x/2023/sections/2/
Week 2 Arrays - CS50x 2023
Harvard University's introduction to the intellectual enterprises of computer science and the art of programming.
cs50.harvard.edu
#include <stdio.h>
#include <cs50.h>
int main (void)
{
int length;
do
{
length = get_int("Length :");
}
while ( length < 1 );
int twice[length];
for (int i = 0, num = 1; i < length; i++, num = num * 2)
{
twice[i] = num;
printf("%i\n", twice[i]);
}
}
위는 작성한 답안
아래는 수업에서 제공된 소스코드
For 문에 조건을 2개 넣을 경우, int를 한번만 써줘야 한다.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// Get user input, make sure it's positive
int length;
do
{
length = get_int("Size of array: ");
}
while (length < 1);
// Declare our array
int array[length];
// Initialize the first value of the array
array[0] = 1;
// Print the first value
printf("%i\n", array[0]);
// Fill in the rest of the array
for (int i = 1; i < length; i++)
{
// Current value is twice the previous value
array[i] = array[i - 1] * 2;
// Print the current value
printf("%i\n", array[i]);
}
}