(Motivation) I am trying to construct a program in C that allows me to (1) Enter a certain amount of numbers in an array (2) Enter what exactly those numbers are (3) Enter a search value from that array that makes the C program find what position that search value is in.
Basically, I am trying to do this.
(Attempt) Here is what I tried so far.
#include <stdio.h>
#include <stdlib.h>
//Write a 'C' program to accept n integers in an array and search for a specific number.
int main()
{
int a[10],n,i,key;
printf("Enter how many numbers in an array: ");
scanf("&d",&n);
printf("Accept n numbers in an array: \n");
for(i=0;i<n;i++)
{
scanf("&d",&a[i]);
}
printf("Display Array Elements\n");
for(i=0;i<n;i++)
{
printf("%d",&a[i]);
}
printf("Enter search value: ");
scanf("%d", &key);
for(i=0;i<n;i++)
{
if (a[i]==key)
printf("Number found at position %d", i+1);
else
printf("Element not found!");
}
return 0;
}
When I compile this in CodeBlocks (version 20.03), I am able to enter in how many numbers there are in an array, but then after typing in a number, say 4, CodeBlocks prints out
Accept n numbers in an array: 4
Display Array Elements
Enter search value:
Process returned 0 (0x0) execution time : 22.628 s
Press any key to continue.
(Question) How can I improve this code such that it does what (1), (2), and (3) above says? I also welcome alternate methods. I have been trying to replicate what the YouTube video in the link says, but I have not been able to succeed.
I want to mention I have little to no coding experience, and I am learning C for the first time. I also tried searching for similar questions, but given my novice skills in coding, I am not able to take advantage of them. Thank you in advance.
At least these problems:
Code not compiled with a well enabled compiler
Use a compiler with all warnings enabled. This rapidly points out many of code's troubles.
warning: too many arguments for format [-Wformat-extra-args]
scanf("&d", &n);
^~~~
warning: too many arguments for format [-Wformat-extra-args]
scanf("&d", &a[i]);
^~~~
warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
printf("%d", &a[i]);
Code attempts to print the address and not the value
Printing with "%d"
and an address and not an int
leads to undefined behavior (UB). Drop the &
.
// printf("%d",&a[i]);
printf("%d", a[i]);
Use %
@Eric Postpischil
Since &d
is not a specifier, "&d"
directs scanf()
to scan in the characters '&'
and 'd'
and then move on. If there or not, code simply moved on and used an uninitialized n
for the rest of code. In OP's case, n
appears to be 0 and so code ended promptly.
// scanf("&d",&a[i]);
scanf("%d", &a[i]);
// ^
Test inputs
Check scanf()
return value. @Shawn
Test range
// scanf("&d",&n);
if (scanf("%d", &n) != 1 || n < 1 || n > 10) {
fprintf(stderr, "Invalid numeric input or out of range 1-10\n");
return EXT_FAILULRE;
}