gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Convert program from Python to C: "print(list(n**2 for n in range(1, 21)))".
- User
Convert program from Python to C: "print(list(n**2 for n in range(1, 21)))".
- Assistant
To convert the provided Python code into C, we will create an array to hold the squared values of numbers from 1 to 20. Since Python automatically manages lists (arrays) and handles memory for us, we'll need to allocate memory in C and print the values using a loop.
Here's the equivalent C code:
#include <stdio.h> int main() { // Create an array to hold the squares of numbers from 1 to 20 int squares[20]; // Calculate squares and store them in the array for (int n = 1; n <= 20; n++) { squares[n - 1] = n * n; // Store the square of n in the array } // Print the array printf("["); for (int i = 0; i < 20; i++) { printf("%d", squares[i]); if (i < 19) { printf(", "); // Print comma for elements except for the last } } printf("]\n"); // Close the array representation and print a newline return 0; }