I would like to know if the number the user enters is number in the array.
Here is my code:
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
if(my_arr[i] == secnum)
{
printf("an ex");
}
}
But it doesn't work.
How can I compare a number with another number in array?
Note: I don't know pointers so I need to do it without pointers.
Why it doesn't work and what is wrong with the code?
You are comparing against just one value rather than all the array elements.
The value of i after the scanf loop is 10 so arr[i] would exceed the
array and could cause Illegal memory access.
Check the comments in the program.
#define ARR_SIZE 10
int main()
{
int my_arr[ARR_SIZE]; //Use ARR_SIZE because if ARR_SIZE changes, 10 won't causing unforseen errors.
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i = 0; i < ARR_SIZE ; i++) // Ensures you are comparing secnum with each array element.
{
if(my_arr[i] == secnum)
{
printf("an ex"); //Do you wish to break here because one you find a match, the goal is attained :)
}
}
}
After the loop, i is equal to ARR_SIZE (10). So you compare my_arr[10] with secnum (0). But my_arr[10], while syntactically correct, points to an undefined value because the size of the array is 10.
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i=0;i<ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i=0;i<ARR_SIZE ; i++)
{
if(my_arr[i]==secnum)
{
printf("Given number is in array\n");
break;
}
}
}
As pointed by OP in comments to one of the answers, OP apparently need a routine to check for the key in an array.
So once we have stored an array and have accepted a key to search, we need to pass this array and key to a search function which will return true or false depending upon whether the key is present in the array or not.
#include <stdbool.h> // We need this for `true` and `false` bool values
bool search(int [], int); // Function declaration
/**** Function Definition *****/
bool search(int numbers[], int key)
{
int i;
for(i = 0; i < ARR_SIZE; i++)
if(numbers[i] == key)
return true;
return false;
}
/** Calling search function from main **/
...
if(search(my_arr, secnum))
printf("Number found in array!\n");
else
printf("Number could NOT be found in array!\n");
To find a value in an array you should iterate through it and compare each value with the wanted number. You should also check the return value of scanf() to control how many item did it actually read. See if this reviewed code is helpfull:
#include <stdio.h>
#define ARR_SIZE 10
int read_numbers(int a[], int size) {
int i = 0;
int r = 0;
while ( i < size ) {
printf("Please, enter a number (%d of %d): ",i+1,size);
r = scanf(" %d",&a[i]); // the space before will ignore any trailing newline
if ( r == EOF ) break; // if scanf fails return
if ( r != 1 ) { // if user don't enter a number, repeat
printf("Wrong input!\n");
scanf("%[^\n]*"); // will read and ignore everything lweft on stdin till newline
continue;
}
++i;
}
return i; // return size, unless scanf fails
}
int find_number(int a[], int size, int x) {
int i = 0;
while ( i < size && a[i] != x ) ++i;
return i; // if x isn't in the array returns size
}
int main()
{
int my_arr[ARR_SIZE];
int secnum = 0;
int i = 0;
int n = 0;
n = read_numbers(my_arr, ARR_SIZE);
if ( n < ARR_SIZE ) {
printf("Warning, only %d numebers read out of %d!\n",n,ARR_SIZE);
} // if happens you have uninitialized elements in array
printf("Now, enter the value you want to find.\n");
if ( read_numbers(&secnum, 1) != 1 ) { // reuse the function
printf("Sorry, an error has occurred.\n");
return -1;
}
i = find_number(my_arr, n, secnum); // If all went right n==ARR_SIZE
if ( i < n ) { // a match has been found
printf("Found!\n");
} else {
printf("Not found.\n");
}
return 0;
}
Related
If the user inputs a value that matches with an int in the array continue the program else quit the program.
My issue is that the function loops the whole array and if it finds one of the values doesnt match it will quit.
//Check if the user input matches with one of the ints in the array
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] != num) {
printf("Invalid input");
exit(0);
}
}
}
void main() {
int arr[3] = { 1, 2, 3 };
int num = 0;
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
printf("\nPLease enter a value which matches with the array %d", num);
scanf("%d", &num);
check(num, arr);
}
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] == num) {
return;
}
}
printf("Invalid input");
exit(0);
}
Your issue is that checks a single element and judges the input on that specific value. If it has run through each value and the function has still not returned, there is not match and we can exit the program.
You have a logic flaw in the check function: you should output the message and quit if none of the values match the input. You instead do this if one of the values does not match. The check always fails.
Here is a modified version:
#include <stdio.h>
//Check if the user input matches with one of the ints in the array
void check(int num, const int arr[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (arr[i] == num) {
// value found, just return to the caller
return;
}
}
// if we get here, none of the values in the array match num
printf("Invalid input: %d\n", num);
exit(1);
}
int main() {
int arr[3] = { 1, 2, 3 };
size_t len = sizeof(arr) / sizeof(*arr); // length of the array
int num;
for (size_t i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Please enter a value which matches with the array: ");
if (scanf("%d", &num) == 1) {
check(num, arr, len);
} else {
// input missing or not a number
printf("Invalid input\n");
}
return 0;
}
You are right, you do exit once arr[i] != num (When the value is not the same as the i:th element in the array).
So, you could change it to: arr[i] == num. If it is the same, perhaps print "You got it!", and a return afterwards.
I tried to write a code to check if a number is a perfect square, but I'm not able to call the function I defined. Where is my mistake?
#include <stdio.h>
#include <math.h>
int isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success");
break;
} else {
continue;
}
}
printf("Fail");
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", n);
isPerfectSquare(n);
return 0;
}
I don't get any answer ("Success" or "Fail").
You must pass the address of n instead of its value in scanf("%d", n);:
scanf("%d", &n);
Note however that your function will print both Success and Fail for perfect squares because you should return from the function instead of just breaking from the loop upon success.
Here is a modified version:
#include <stdio.h>
void isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success\n");
return;
}
}
printf("Fail\n");
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
isPerfectSquare(n);
}
return 0;
}
Note also that your method is quite slow and may have undefined behavior (and produce false positives) if i becomes so large that i * i exceeds the range of type int. You should instead use a faster method to figure an approximation of the square root of n and check if the result is exact.
It is also better for functions such as isPerfectSquare() to return a boolean value instead of printing some message, and let the caller print the message. Here is a modified version using the Babylonian method, also known as Heron's method.
#include <stdio.h>
int isPerfectSquare(int number) {
int s1 = 2;
if (number < 0)
return 0;
// use the Babylonian method with 10 iterations
for (int i = 0; i < 10; i++) {
s2 = (s1 + number / s1) / 2;
if (s1 == s2)
break;
s1 = s2;
}
return s1 * s1 == number;
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
if (isPerfectSquare(n)) {
printf("Success\n");
} else {
printf("Fail\n");
}
}
return 0;
}
I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.
Does anyone know why my code is printing "Incorrect PIN entered"
after the if statement, instead of "Correct PIN entered"? When I change the if statement to (input_pin != current_pin) it works.
#include <stdio.h>
#define PIN_SIZE 4
main()
{
int input_pin[PIN_SIZE];
int current_pin[PIN_SIZE] = {1,2,3,4};
int i;
for(i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf("%d", &input_pin[i]);
}
if(input_pin == current_pin)
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
flushall();
getchar();
}
The if(input_pin == current_pin) is comparing two integer arrays. In C, arrays are represented internally as pointers. It's just as if you were comparing two int * variables. Because input_pin and current_pin are actually different arrays, the two pointers will never compare as equal.
To accomplish the comparison you're trying to make, you will need to compare each element of each PIN individually.
You do not have to use an array in this case
#include <stdio.h>
int main()
{
int input_pin = 0;
int current_pin = 1234;
printf("Enter PIN: ");
if ( ( scanf("%d", &input_pin)) == 1) { // successful scanf == 1. one item read
if(input_pin == current_pin)
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
}
}
EDIT:
Using a char array will be easier as strcmp will compare all the elements. If all the elements match, strcmp will return 0. the char arrays must be '\0' terminated.
#include<stdio.h>
#include<string.h>
#define PIN_SIZE 4
int main()
{
int i = 0;
char input_pin[PIN_SIZE+1] = {0}; // PINSIZE+1 to allow for terminating '\0'. set all elements five elements to 0
char current_pin[PIN_SIZE+1] = {"1234"};
for( i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf(" %c", &input_pin[i]); // skip whitespace scan one character
}
if(strcmp( input_pin,current_pin) == 0) // if all elements match == 0
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
return 0;
}
An int array can be used but a flag will be needed allow for checking each element
#include<stdio.h>
#include<string.h>
#define PIN_SIZE 4
int main()
{
int i = 0;
int isMatch = 1; // flag to check matching elements
int input_pin[PIN_SIZE] = {0}; // set all elements to 0
int current_pin[PIN_SIZE] = {1,2,3,4};
for( i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf("%d", &input_pin[i]);
if( input_pin[i] != current_pin[i]) // check each element
{
isMatch = 0; // if an element does not match, reset to 0
}
}
if( isMatch == 1) // isMatch did not get reset to 0
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
return 0;
}
write a program that enter a series of integer(stores in array),then sorts the integer by calling the function selection_sort. When given an array with n elements, selection_sort must do the following:
1.search the array to find the largest,then move it to the last position.
2.call itself recursively to sort the first n-1 elements of the array.
following is my code i think the code is errors everywhere i hope some master can help me
#include <stdio.h>
int selection_sort(int a[])//this function have error that "i"and"count"is undeclared
{
int max = 0;
for (i = 1; i <= count; i++)// continuous compare to final
{
if (a[i] > max)
{
max=a[i];
}
}
a[count] = a[i]; //put the max to last position
count--;
}
int main(void)
{
int a[100] = { 0 },i=0,count=0;
while (1)
{
scanf("%d",&a[i]);
if (a[i] = '\n') { break; }//this line have error because '\n' not "int" so when i "enter" it would not break
i++;
count++; //counting how many integer i scanf
}
selection_sort();//call this function (i don't know well about function so i don't known where to put is correct )
return 0;
}
You have to compare. BUt you are assigned..
change this if (a[i] = '\n') { break; } to if (a[i] == '\n') { break; }.
You should change follows in your code.
1) change your function call..
2) declare count and i in function..
3) for taking values in to array,follow other method..
Try yourself...
Here is the complete code.Basically there are many syntax and logical error in your code. Consider this as refer and compare with your original source.
int selection_sort(int a[], int count){
int max = 0, i =0;
for (i = 0; i < count; i++){
if (a[i] > max)
{
max=a[i];
}
}
a[count] = max;
count--;
return 0;
}
int main(void) {
int a[100] = { 0 },i=0,count=0;;
printf ("Enter the total num\n");
scanf("%d",&count);
if ( ( count ) >= (sizeof(a)/sizeof(a[0])) )
return -1;
while (i < count){
scanf("%d",&a[i]);
i++;
}
selection_sort(a, count);
printf ("\nmax:%d\n", a [count]);
return 0;
}