首页 > 解决方案 > 我如何在不使用数组的情况下解决问题,因为数组现在对我来说很复杂?

问题描述

问题是:- 编写一个 C 代码,要求用户输入 10 个数字,然后要求他输入另一个数字以在 10 个数字中搜索并打印其位置以防万一。如果没有找到号码,它将打印号码不存在。

我写的代码是:-

#include<stdio.h>
void main(void)
{
    int n, i, value,j;

    for (i=1;i<=10;++i)
    {
        printf("enter number %d : ",i);
        scanf("%d",&n);

    }
    printf("Enter the value to search: ");
    scanf("%d",&value);
     /*next part of code is not correct 
        that can not search to find the place of number */
    for (j=1;j<=10;++j)
    { 
        if (value == n)
        {
            printf("value is exist at element number %d",n);

        }
        else 
        {
            printf("value is not exist\n");
        }

    }
}

输出将是:-(输入数字后)。

Enter the value to search is 12.  
value is exist at element 9

标签: c

解决方案


#include <stdio.h>


int main(){
    //there are 10 int in n
    int n[10], i, value;



    for (i=0;i<10;i=i+1)//array count from 0 ,i=i+1 same as i++ 
    {
        printf("enter number %d : ",i);
        scanf(" %d",&(n[i]));//& mean get address so you will push what you input to n[0]~n[9]
        //little tip  before %d remain a space for some reason if you keep learn you will know


    }
    printf("Enter the value to search: ");
    scanf(" %d",&value);//& mean get address so you push what you input to value here

    for (i=0;i<10;i=i+1)
    { 
        if (value == n[i])
        {
            printf("value is exist is element number %d\n",n[i]);
            break;//break mean out of for loop
            //
        }

    }
    if(i==10){//if search all not found then i will be 10 because after loop i will +1
        //if break i will not +1
        printf("value is not exist\n");
    }
        return 0;//remember "int" main() so you need return 0 
}

不断学习你会更强大 数组很简单


推荐阅读