Write a program to find the sum of 10 natural numbers using for loop and while loop, respectively
时间: 2024-02-04 09:04:25 浏览: 23
使用 for 循环计算 10 个自然数的和:
```python
# 使用 for 循环计算 10 个自然数的和
sum = 0
for i in range(1, 11):
sum += i
print("The sum of first 10 natural numbers is:", sum)
```
输出结果为:
```
The sum of first 10 natural numbers is: 55
```
使用 while 循环计算 10 个自然数的和:
```python
# 使用 while 循环计算 10 个自然数的和
sum = 0
i = 1
while i <= 10:
sum += i
i += 1
print("The sum of first 10 natural numbers is:", sum)
```
输出结果为:
```
The sum of first 10 natural numbers is: 55
```
以上两段代码都是可以计算 10 个自然数的和的,只是使用了不同的循环方式。
相关问题
Write a program to find the sum of N natural numbers using for loop and while loop, respectively
Sure, here's the solution in Python:
Using for loop:
```
# Taking input from user
n = int(input("Enter a positive integer: "))
# Initializing the sum variable
sum = 0
# Using for loop to calculate sum of first n natural numbers
for i in range(1, n+1):
sum += i
# Displaying the sum
print("Sum of first", n, "natural numbers is:", sum)
```
Using while loop:
```
# Taking input from user
n = int(input("Enter a positive integer: "))
# Initializing the sum variable
sum = 0
# Using while loop to calculate sum of first n natural numbers
i = 1
while i <= n:
sum += i
i += 1
# Displaying the sum
print("Sum of first", n, "natural numbers is:", sum)
```
Both programs achieve the same result, i.e., finding the sum of first N natural numbers.
用c语言Write a program to print the sum of individual rows and columns of the given 3x 3 matrix
以下是用 C 语言编写的程序,用于打印给定 3x3 矩阵的每行和每列的总和:
```c
#include <stdio.h>
int main()
{
int matrix[3][3];
int row_sum[3] = {0};
int col_sum[3] = {0};
// 获取矩阵的输入值
printf("Enter the elements of the matrix:\n");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
scanf("%d", &matrix[i][j]);
row_sum[i] += matrix[i][j];
col_sum[j] += matrix[i][j];
}
}
// 打印矩阵和每行/列的总和
printf("The matrix and the sum of individual rows and columns are:\n");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
printf("%d ", matrix[i][j]);
}
printf("%d\n", row_sum[i]);
}
for(int j=0; j<3; j++)
{
printf("%d ", col_sum[j]);
}
return 0;
}
```
该程序首先声明了一个 3x3 的整型数组,然后声明了两个长度为 3 的整型数组,以存储每行和每列的总和。接下来,使用嵌套循环获取矩阵的输入值,并将它们添加到相应的行和列总和中。
最后,使用嵌套循环打印矩阵和每行/列的总和。在每行的循环中,打印矩阵中的元素,然后打印该行的总和。在列的循环中,只需打印每列的总和即可。
希望对你有所帮助!