c - 打印数组的元素,直到 C 编程中指定的键

标签 c arrays

我一直在努力提高我的编码技能,并开始了我的旅程。因为我被困在一个地方并试图弄清楚我哪里出错了。代码是这样的:

#include<stdio.h>
int main(){
   int a[10],i,j,arr_size;

   printf("Enter the size of the array");
   scanf("%d",&arr_size);

   printf("Enter the array:");
   for(i=0;i<arr_size;i++)
   scanf("%d",&a[i]);

   //here key is 42
   //so we'll find the key and print the elements up to that
   for(j=0;j<arr_size;j++){
      if(j==42)
        break;

      //loop for the array up to the key
      for(i=0;i<j;i++)
      printf(" %d",a[i]);  
   }

   return 0; 
}

输出是: The output of the above code

输出显示循环一直到键,即 42,但以不同的方式打印 1 1 2 1 2 42。现在这很奇怪。

要求的输出必须是格式:1 2 仅当给定输入时 1 2 42 33

最佳答案

试试这个..

#include<stdio.h>
int main(){
   int a[10],i,j,arr_size;

   printf("Enter the size of the array");
   scanf("%d",&arr_size);

   printf("Enter the array:");
   for(i=0;i<arr_size;i++)
   scanf("%d",&a[i]);

   //here key is 42
   //so we'll find the key and print the elements up to that
   for(j=0;j<arr_size;j++){
        if(a[j]==42) 
          break;
    }
   //loop for the array up to the key
   for(i=0;i<j;i++)
    printf(" %d",a[i]);  


   return 0; 
}

此代码将给出所需的输出.. 1 2

关于c - 打印数组的元素,直到 C 编程中指定的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44859290/

相关文章:

c - 为什么两个变量共享同一个地址?

c - 从动态规划函数中获取值

arrays - 删除行和列的数组

javascript - 通过 POST 将 JavaScript 数组发送到 PHP

c - 在C中初始化库外.lib的函数指针

c - 如何使用结构将指针值从单独的函数传递回 main

c - count[i]++ 是什么意思

arrays - 通过 [String][String] 进行嵌套数组/对象访问

java - 部分填充的数组 - 获取最小值和 toString

c - 两种声明有什么区别?