如何编写一个 C 语言程序,使用 For 循环、While 循环和函数来打印数组中的负数,并附带示例。
C 语言打印数组中的负数程序
此程序允许用户输入一维数组的大小和元素。接下来,我们使用 For 循环来迭代数组值并查找 C 语言中的负数。
/* C Program to Print Negative 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 Negative Numbers in this Array : ");
for(i = 0; i < Size; i ++)
{
if(a[i] < 0)
{
printf("%d ", a[i]);
}
}
return 0;
}

在此,For 循环将确保该数字在 0 和一维数组的最大大小值之间。在此示例中,它将是 0 到 7。
for(i = 0; i < Size; i ++)
在下一行,我们声明了 If 语句。
if(a[i] >= 0)
任何小于 0 的数都是负数。If 语句中的条件将检查此情况。如果条件为真,则该数为负数,C 语言编译器将打印这些值。
使用 While 循环打印数组中的负数的程序
此程序与上述程序相同,但这次我们使用了 While 循环来打印数组中的负数。
/* C Program to Print Negative 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 Negative Numbers in this Array : ");
while(j < Size)
{
if(a[j] < 0)
{
printf("%d ", a[j]);
}
j++;
}
return 0;
}
Please Enter the Size of an Array : 5
Please Enter the Array Elements : -12 59 -89 28 -16
List of Negative Numbers in this Array : -12 -89 -16
使用函数打印数组中负数的程序
这个打印数组中负数的程序与第一个示例相同。但是,我们使用 函数将打印数组中负数的逻辑分开了。
/* C Program to Print Negative Numbers in an Array */
#include<stdio.h>
void PrintNegativeNumbers(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]);
}
PrintNegativeNumbers(a, Size);
return 0;
}
void PrintNegativeNumbers(int a[], int Size)
{
int i;
printf("\n List of Negative 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 : -15 -89 22 19 -56 88 97 -59 -105 179
List of Negative Numbers in this Array : -15 -89 -56 -59 -105