What in the world, is the matter here:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int array[20];
int *pArray = array;
int count;
int i = 0;
while(1)
{
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
i++;
}
printf("Contents: ");
while(1){
if (*(pArray + i) != -1)
{
printf("%d ", *(pArray + i) );
i++;
}
}
return 0;
}
Thank you. I am trying to take input from the user and then display the contents of the array. I was going to arrange them in order too using pointers, but I'll wait till someone replies.
Here is my rewrite attempt:
#include <stdio.h>
int main(void)
{
int array[20];
int i = 0;
while(1)
{
scanf("%d", &array[i] );
if(array[i] == -1) break;
i++;
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(1)
{
if (array[i] != -1)
{
printf("%d ", array[i] );
i++;
}
}
return 0;
}
You may be facing the error of stack around the variable array is corrupted. The reason is that you are first taking an input and then terminating the loop if the given input was -1.
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
Now assume that i=20 what will happen???
Of course your code will crash on the scanf statement because it will try to access array+20 (the 20th index) which will not be allowed.
You also need to initialize the array first because when you declare an array, it contains junk values perhaps initializing the last index with zero will do the job. You can use the following code:
#include <stdio.h>
int main(void)
{
int array[20];
/*INITIALIZE THE LAST INDEX WITH -1 TO APPLY THE TERMINATING CONDITION*/
array[19] = -1;
int i = 0;
while(1)
{
scanf("%d", array+i );
i++; //INCREMENT HERE TO CHECK THE NEXT INDEX INSTEAD OF CHECKING THIS ONE
if(array+i == -1)
{
scanf("%d", array+i ); //TAKE THE INPUT FOR THE LAST INDEX
break; //TERMINATE THE LOOP
}
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(i != 20)
{
printf("%d ", array[i] );
i++;
}
return 0;
}
It seems like you are using pArray without any reason. array can also do exactly what you are trying to do with pArray. For arranging the order, you have to apply any sorting algorithm. Hope this helps.
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 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;
}
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;
}
I am trying to run a program that will repeatedly read a letter from the user, with the most being entered as 12. If the user enters a sentinel value that they input, the loop should terminate. However, as soon as the first character is read in the loop, it terminates.
Also, the program will place the same word in the reverse order in another array, then check them to see if the first array (read forward), is the same as the other array (read backward). If it is, it displays that the word is a palindrome.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int charCount, counter, i, temp, check,check2;
char letter[12], letter2[12];
charCount = 0;
counter = 10;
check = 0;
i = 1;
check2 = 0;
printf("Enter your sentinel value.:");
scanf_s(" %c", &letter[check2]);
while ((i<13) && (letter[i] != letter[check2]))
{
printf("Enter individual letters in word (in order).:");
scanf_s(" %c", &letter[i]);
charCount++;
if (letter[i] == letter[check2])
{
break;
}
i++;
}
printf("Letters entered:%i\n", charCount);
for (i = 0; i < charCount; i++)
{
letter2[i] = letter[i];
}
for (i = 0; i <= (charCount / 2); i++)
{
temp = letter2[counter];
letter2[counter] = letter2[i];
letter2[i] = temp;
counter--;
}
for (i = 0; i <= charCount; i++)
{
if (letter[i] = letter2[i])
{
check++;
}
}
if (check = charCount)
{
printf("Word is a palindrome.\n");
}
system("PAUSE");
return 0;
}
the letter[1] value will be unassigned when the while loop enters for the first time right ? I think you can take that condition out of the while loop since you are considering it in the if statement inside the while loop
I had a bunch of problems with this program but looks like this might be inches away from completion and I was hoping someone could tell me what the hell's wrong with the blasted thing!
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING], int);
int shortestArray(char [][SIZE_OF_STRING], int);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[1000][SIZE_OF_STRING];
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
n++;
printf("Enter %d names", n - 1);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array, n);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array, n);
printf("Shortest name is %s in position %d\n", array[position], position + 1);
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
gets(a[i]);
}
}
void printArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
puts(a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i;
int chag = 0;
int position;
while (a[i] != '\0')
{
if (strlen(a[i]) < strlen(a[i-1]))
{
position = i;
chag = 1;
}
else
{
if (chag = 0)
{
position = 1;
}
else
{
printf("");
}
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}
only worried about "shortest" function at the moment all others run okay.
I also know there are better ways of doing the search but I keep getting "declaration creates integer from pointer without cast" errors when I change to a more standard search with a default smallest etc.
chag is to say whether or not number one in a[] is the smallest as it never gets checked, going to change this as soon as I get it working as I can see a more effective way of doing it.
[edit]
My bad, the error that appears is an application error when "smallest" is selected.
the following appears
"the instruction at "0x77c478c0" referenced memory at "0xd2fd82e0". the memory could not be "read".
ok to terminate program, cancel to debug.
changed the shortest function to the following and still get a similar memory message;
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i = 1;
int position = 1;
while (a[i] != '\0')
{
if (strlen(a[i + 1]) < strlen(a[i]))
{
position = i + 1;
i++;
}
else
{
i++;
}
}
return position;
}
There's a clbuttic typo in shortestArray():
if (chag = 0) {
position = 1;
}
// ...
This will always evaluate to false, so the else block is run.
Here, zero is assigned to chag which makes the expression evaluate to zero (false). Use the comparision operator == instead. You might want to crank up warning levels as I'm sure, any C compiler has an appropriate message for this.
One big and obvious problem is that in the function you use the variable i without initializing it.
Another problem is this expression: strlen(a[i-1]). If i is 0 then this will access memory before the array.
In addition to the other answers so far:
You don't increment i either.
If I imagine all the trivial fixes applied (correct iteration, comparison instead of assignment in the condition), the function is going to return position of last local minimum of length. I.e. having list of strings like
"a", "bbbb", "ccc", "dd"
it will return 3, but shortest string is at position 0!
You do remember array indices in C start from 0, right (in position = 1)?
you have to know the number of strings entered in the array to avoid unknown behavior.
a way to do this : in main, just after declaration of array, put :
strcpy(array[0], ""); // to indicate that the array is empty.
in the end of readArray() :
strcpy(a[n] , ""); // there is n strings written bythe user (a[0] to a[n-1]).
and finally :
in shortestArray(), the stop condition of the loop must be changed to :
while (strcmp(a[i],"") != 0 ) //a[i] == '\0' is not correct because a[i] is string and '\0' is char.
here is the entire code with the changes i made :
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
#define SIZE_OF_ARRAY 1000
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING]);
int shortestArray(char [][SIZE_OF_STRING]);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[SIZE_OF_ARRAY][SIZE_OF_STRING]; //change here !
strcpy(array[0] , ""); //instruction added : means array is empty
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
while (n >= SIZE_OF_ARRAY)
{
printf("the number you entered is bigger than the maximum number of strings, please enter a number smaller than %d\n", SIZE_OF_ARRAY);
}
printf("Enter %d names", n);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array);
if (position == -1)
printf("there is no string entered !\n");
else
printf("Shortest name is %s in position %d\n", array[position-1], position );
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
scanf("%s",a[i]);
}
strcpy(a[n] , "");
}
void printArray(char a[][SIZE_OF_STRING])
{
int i;
for (i=0; i< SIZE_OF_ARRAY; i++)
{
if (strcmp(a[i] , "") == 0) // a[i-1] is last string entered
break; // this avoid printing non initialized string causing unknown behaviour.
printf("%s\n",a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING])
{
int i = 0;
int position = 1;
if(strcmp (a[i] , "\0") == 0)
return position = -1; // there no string entered.
while (strcmp (a[i+1] , "\0") != 0)
{
if (strlen(a[i+1]) < strlen(a[i]))
{
position = i+2 ;
i++;
}
else
{
i++;
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}