自己总结了一下关于一维数组的常见例子:
Dawn.L
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
int a[10] = {1,2,3,4,5,6,7,8,9,0};
//正向遍历
for (int i = 0; i < 10; i++)
{
if (i % 3 == 0)
printf("%d ", a[i]);
}
printf("\n");
//反向遍历
for (int i = 9; i>= 0; i--)
{
printf("%d ", a[i]);
}
printf("\n");
//从键盘输入一个整数,判断这个整数是否有重复的数字
int x;
NSLog(@"请输入一个整数:");
scanf("%d", &x);
BOOL bs[10] = {NO};
do
{
int n = x % 10;
if (bs[n] == YES)
{
NSLog(@"数字%d重复了", n);
break;
}
bs[n] = YES;
x /= 10;
}while (x);
if (x == 0)
{
NSLog(@"没有重复的数字");
}
}
return 0;
}
#import <Foundation/Foundation.h>
//数组打乱顺序
int main()
{
@autoreleasepool {
int a[10] = {0,1,2,3,4,5,6,7,8,9};
for (int i = 0; i < 10; i++)
{
int x = rand() % (10 - i - 1) + i + 1;
int temp = a[i];
a[i] = a[x];
a[x] = temp;
}
for (int i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
return 0;
}
#import <Foundation/Foundation.h>
//数组元素是否重复
int main()
{
@autoreleasepool {
int a[10] = {1,2,3,4,5,6,7,8,9,0};
BOOL flag = NO;
int i = 0;
for (; i < 10; i++)
{
int j = i + 1;
for (; j < 10; j++)
{
if (a[i] == a[j])
{
flag = YES;
NSLog(@"第%d个元素与第%d个元素重复了", i + 1, j + 1);
//break;
}
}
// if (j < 10)
// {
// break;
// }
}
if (flag == NO)
{
NSLog(@"没有重复的元素");
}
}
return 0;
}
#import <Foundation/Foundation.h>
//经典例子:双色球
int main()
{
@autoreleasepool {
srand((unsigned)time(0));
int blue = rand() % 16 + 1;
int red[6];
for (int i = 0; i < 6; i++)
{
red[i] = rand() % 33 + 1;
for (int j = 0; j < i; j++)
{
if (red[i] == red[j])
{
i--;
break;
}
}
}
printf("蓝:%d\n", blue);
printf("红:");
for (int i = 0; i < 6; i++)
{
printf("%d ", red[i]);
}
printf("\n");
}
return 0;
}