如何使用 For 循环、While 循环和函数编写 C 语言数组正数打印程序,并附有示例。
C 语言数组正数打印程序
此程序允许用户输入一维数组的大小和元素。接下来,我们使用 For 循环来迭代数组值并查找正数。
/* C Program to Print Positive Numbers in an Array */
#include<stdio.h>
int main()
{
int Size, i, a[10];
printf("\n Please Enter the Size of an Array : ");
scanf("%d", &Size);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
printf("\n List of Positive Numbers in this Array : ");
for(i = 0; i < Size; i ++)
{
if(a[i] >= 0)
{
printf("%d ", a[i]);
}
}
return 0;
}

在这里,For 循环将确保该数字在 0 和最大一维数组大小值之间。在此示例中,它将从 0 到 4。
for(i = 0; i < Size; i ++)
在下一行,我们声明了If语句
if(a[i] >= 0)
任何大于或等于 0 的数字都是正数。If 语句中的条件将检查相同内容。如果条件为 True,则它是正数,并且C 编程编译器将打印这些值。
使用 While 循环打印数组正数的程序
此程序与上面的程序相同,但这次我们使用了While 循环来打印数组中的正数。
/* C Program to Print Positive Numbers in an Array */
#include<stdio.h>
int main()
{
int Size, i, j = 0, a[10];
printf("\n Please Enter the Size of an Array : ");
scanf("%d", &Size);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
printf("\n List of Positive Numbers in this Array : ");
while(j < Size)
{
if(a[j] >= 0)
{
printf("%d ", a[j]);
}
j++;
}
return 0;
}
C 语言使用 while 循环打印数组中的正数输出
Please Enter the Size of an Array : 8
Please Enter the Array Elements : 12 -25 -89 19 -22 48 79 125
List of Positive Numbers in this Array : 12 19 48 79 125
使用函数打印数组正数的程序
此程序与第一个示例相同。但是,我们已经将使用函数打印数组中的正数的逻辑分开了。
/* C Program to Print Positive Numbers in an Array */
#include<stdio.h>
void PrintPositiveNumbers(int a[], int Size);
int main()
{
int Size, i, a[10];
printf("\n Please Enter the Size of an Array : ");
scanf("%d", &Size);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
PrintPositiveNumbers(a, Size);
return 0;
}
void PrintPositiveNumbers(int a[], int Size)
{
int i;
printf("\n List of Positive Numbers in this Array : ");
for(i = 0; i < Size; i++)
{
if(a[i] >= 0)
{
printf("%d \t ", a[i]);
}
}
}
Please Enter the Size of an Array : 10
Please Enter the Array Elements : -12 14 -56 98 16 -78 105 569 -3 100
List of Positive Numbers in this Array : 14 98 16 105 569 100