User Enters 10 Numbers into an Array How Would I Write Code to Find That Number and Output What Position It Is in the Array

user enters 10 numbers into an array how would I write code to find that number and output what position it is in the array?

This will return the index of thingToFind, or -1 if thingToFind is not found.

 public static int find(int[] arr, int thingToFind){
int i;
for(i = 0; i < arr.length(); i++){
if(arr[i] == thingToFind){
return i;
}
}
return -1;
}

Write a programme to input 10 numbers from the user and print greatest of all

If you have an array declared like

int a[N];

where N is some positive integer value then the valid range of indices to access elements of the array is [0, N).

It means that for example this for loop

for(i=1;i<=10;i++)
{
printf("enter 10 nos. for arr[%d] :",i);
scanf("%d",&arr[i]);
}

must look like

for ( i = 0; i < 10; i++ )
{
printf("enter 10 nos. for arr[%d] :",i);
scanf("%d",&arr[i]);
}

This while loop

    while(arr[i]>c)
{
c=arr[i];
}

just does not make a sense and can be an infinite loop.

Moreover this call of printf

    printf("Greatest number in a given array is:%d",c);

is placed within a for loop.

The program can look the following way

#include <stdio.h>

int main( void )
{
enum { N = 10 };
int arr[N];

printf( "Enter %d numbers:\n", N );

for ( int i = 0; i < N; i++ )
{
printf("\t%d: ", i + 1 );
scanf( "%d", arr + i );
}

int max = 0;

for ( int i = 1; i < N; i++ )
{
if ( arr[max] < arr[i] ) max = i;
}

printf( "The greatest number in the given array is: %d\n", arr[max] );

return 0;
}

Trying to find a number in an array with an input and print if it is not equal to the input

Your code is comparing the user's input with just the first element of the array, i.e. array[0]. What you need to do is to loop through the whole array and compare the number with every element of the array.

Write a program that asks the user for up to 10 integers (it could be fewer); using arrays, and for loops

First, in your while loop, you are using i to assign the values in the array, you need num instead. Second, num should be set to zero so that the first element of the array is filled. Try this code:

#include <iostream>
#include <string>
using namespace std;


int main( ) {
int max = 10;
int num = 0;
int userVal[max];
int i = 0;


while(num <= max) {
cout << "Enter a number (0 to stop): ";
int number;
cin >> number;

cout << number << endl;
if(number == 0) {
break;
}

userVal[num] = number;
++num;

}
cout << num << endl;
cout << "Your numbers in reverse order are: " << endl;
for(i = num; i >= 0; --i) {
cout << userVal[i];
if(i < num - 2) {
cout << ", ";
}
}

return 0;
}


Related Topics



Leave a reply



Submit