Compare a single integer against an array of integers in C? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How does one compare a single integer to an array of ten integers to find if the single integer is contained within the array using C language? My apologies if original question was unclear, while swipe is equal to any number within the array I want to output PORTD=0b10000000. Thank you!
short a[10]={10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; //Array of accepted passwords.
short array[10];
int i;
for(i=0; i<10; i++){
array[i]=a[i];
}
srand(clock());
while(1){
int swipe=rand() % 20; /* Simulated code read from card swipe, in this
* instance we used a random number between
* 1 and 20.*/
for(i=0; i<10; i++){
if(swipe == array[i]) {
PORTD=0b10000000;
} else {
PORTD=0b00001000;
} //If swiped code evaluates as one of the approved codes then set PORTD RD7 as high.
}
char Master=PORTDbits.RD7;
This seems to have solved it...thanks for all of your help!
for(i=0; i<10; i++){
if(swipe == array[i]) {
PORTD=0b10000000;
break;
} else {
PORTD=0b00001000;
}
}

You need to test your swipe value against ALL ten values in your array of accepted passwords.
e.g. like below
for(i=0; i<10; i++)
if(swipe == array[i]) {
set a true flag (and maybe exit the for loop)
}
Depending on the flag, set the output

In addition to #kaylum's answer...
Because you are calling rand() in a loop, you need to call srand() first before entering the loop,
srand(clock());//for example
while(1){
LATD=0x00;
int swipe=rand() % 20;
...
If you do not, the random numbers you get will be the same sequence of values every time you execute.
Additionally, if i is not reinitialized before being used to compare, it is == 10. It needs to be reset before using as your array index...
Also, in your code, it appears you want to check the latest random number against the 10 accepted passwords. If that is correct, you must compare all 10 of them:
int main(void)
{
srand(clock());//for example
j = 0;
while(1)
{
int swipe=rand() % 20;
PORTD=0b00000000;
for(i=0;i<10;i++)
{
j++;
if(swipe == array[i])
{
PORTD=0b10000000;
break;
}
}
//to show ratio of legal to illegal passcodes...
printf("times through: %d Value of PORTD %d\n", j, PORTD);
}
}

if(swipe == a[i]). That invokes Undefined Behaviour as i is 10 and 10 is an out of bounds index. The valid indexes are from 0 to 9.

You are trying to simulate random card-reading actions & get both Pass/Fail at different instances. With swipe values between 1 to 20 and passwords only in the range 10, 19, you'd like to see if some instances fail. Is that correct?
If so, considering your rand() function returns only integer, set a breakpoint and probe for value of swipe. It seems to always has same value. Make rand() function better for wider statistical distribution. There are many sources to generate random integers like Linear Congruential Method etc.
Also that comparison should be looped for every value of array.

Related

Print if there is a number combination that equals the given number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I had this question in my exam a few weeks ago (Failed to answer it) and I wanted to know how to solve this kind of questions because I see they repeat themselves.
Write C program that gets Integers till -1 is inserted. if certain product of previously written numbers is equal to the last entered integer - the program will print it.
I know its pretty hard to understand but here are few examples :
(Typed order left to right)
1 -> 2 -> 3 -> 6 (Will print 2 * 3=6) -> 36 (Will print 2 * 3 * 6) -> -1
I can see that the problem is hard to do with arrays because of the memory limitation...
so I though of using "List" but ain't got idea how to.
I don't want a complete solution! I would like to get any hint on how to solve it in C (C# is also ok but C preferred).
Use a do-while cycle with condition and a counting sort.
https://en.wikipedia.org/wiki/Counting_sort
I wrote a raw program that does what you want with the exception that it always considers 1 as the product of previous numbers, and the same is true for numbers that were already entered. I leave you the challenge to fix the issue.
#include <stdio.h>
#define SIZE 10
void combo( int pro, int sum );
int n[SIZE], found, i;
int main() {
for( ; i < SIZE && scanf("%d", &n[i]) == 1 && n[i] != -1; i++) {
found = 0;
combo(1,0);
if( found ) printf("%d ", n[i]);
}
return 0;
}
void combo( int pro, int sum )
{
if( pro == n[i] ) found = 1;
for(int j = 0; j < i - sum && !found; j++) {
combo(pro * n[j], sum + 1);
}
}
n, found, i don't have to be global variables, but since combo could call itself lots of times, I thought it would have been a good idea to avoid giving it many arguments. I really don't know if it actually is a good idea.
Anyway, the program is a brute force. combo() will try every possible products of the elements of n.
For each j, combo will call itself generating a new loop, and for each index of this new loop there will be another recursive call generating a whole new loop, and so on.
combo stops to call itself when all the loops stop running.
A loop stops when either a matching product has been found or j reaches i - sum, where i is the current number of elements stored in the array minus 1, while sum represents the number of elements involved in the current product.
Every time, before to enter a loop, the function checks whether the current product matches the last number entered in the array.
If you know that the numbers are entered in ascending order you can optimize by swapping !found with pro < n[i].
I haven't done the math, but in case the input consists in a sequence of random integers, it may be more efficient to sort the array before to call combo in main.

need help generating random characters for memory match game in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm developing a console game in c :
I've writed functions to print the game map in console (memory match like),
in each space that should contain a letter has been replaced with "?" symbol.
know I managed to develop this functionality with this idea :
rand()%26 + 65
as far as I know, the following command allows me to print a letter of the alphabet using integers.
My problem is to figure out how to generate random pairs of characters from the alphabet and place them in order to make a fully memory working game.
I'm so confused about the processing development of this game and I don't where to look. Someone has any ideas on how to do it?
Keep in mind that the rand() function is a pseudo random number generator. Even when seeded with its companion function: srand(), it is not guaranteed to produce purely random numbers. To use it successfully in the manner you have described, i.e. obtaining a list of unique values from some min to some max, it needs help...
Following are examples of companion functions that work in conjunction with the rand() pseudo-random generator to provide a list of values, guaranteed unique, between some min and some max:
Summary: int random = (rand()/32767.0)*max; will return a number no bigger than max which is then tested for value >= some min.
#include <stdlib.h> //defines rand(), srand() and RAND_MAX
int randomGenerator(int min, int max)
{
int random, trying;
srand(clock());//seed the rand() function before using it
//call frequency must be less than clock tick frequency
//or values will repeat.
// (problem with the word pseudo)
trying = 1;
while(trying)
{
//random = (rand()/32767.0)*max;
random = (rand()/(float)RAND_MAX)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
To obtain the complete list of unique values needed, keep a list of previously obtained values (within 'A' to 'Z') and exclude them as they are returned until you have a sequenced through a unique set. Perhaps something like this example:
BOOL filled(int *p, size_t size)
{
int i;
BOOL results = TRUE;
for(i=0;i<size;i++)
{
if(p[i] == 0)
{
results = FALSE;
}
}
return results;
}
Example usage of both functions together:
int main(void)
{
int result, i;
int c='g';
int previous['Z'-'A'+1] = {{0}}; //size array to contain alphbet,
//initialize all elements
size_t size = sizeof(previous)/sizeof(previous[0]);
while(c != 'q')
{
while(!filled(previous, size))
{
result = randomGenerator('A', 'Z');
if( previous[result - 'A'] != 1)
{
previous[result -'A'] = 1;
printf("%c\n", result);
}
Sleep(1); // 1ms delay to avoid aliasing the clock() function
}
printf("finished!\n");
printf("'q' to quit, any other key to continue\n");
c = getchar();
memset(previous, 0, size*sizeof(int));
}
return 0;
}

My C program outputs undesired array values [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've been tasked to code a program that processes a simple 1D array to return its element values, but the compiler has been behaving strangely; outputting more values than I have array elements.. It's also not being fully compliant with one of my statements (one that prints a new line character every 8 elements) and not assigning the largest value to my variable. I think that the other two problems will go away once the first problem is fixed, however.
Here is my brief:
Design, code and test a program that:
Fills a 20 element array (marks) with random numbers between 0 and 100.
Prints the numbers out 8 to a line
Prints out the biggest number, the smallest number and the average of the numbers
And here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int marks[20];
int i = 0;
int sum = 0;
int min;
int max;
for(i;i<=sizeof(marks);i ++){
marks[i] = rand() % 100;
sum += marks[i];
if(i % 8 == 0){
printf("\n");
}
printf("%d ", marks[i]);
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
}
printf("\n\nThe minimum value is: %d", min);
printf("\nThe maximum value is: %d", max);
printf("\n\nThe average value is: %d", sum / sizeof(marks));
return 0;
}
Please can someone help me get the correct output?
sizeof() function returns the byte length of the array, so this code "thinks" your array is 20 * whatever byte size ints are on your machine. You will want to just use i < 20 in the loop or go
for (i;i<sizeof(marks)/sizeof(int); i ++) { ...
Note that you probably do not want the <= operator in the for loop, since arrays are 0 indexed, thus marks[20] is actually one beyond the array.
There are two problem I can see that will invoke undefined behavior in your code.
By saying for(i;i<=sizeof(marks);i ++), you're out of bounds.
int min; int max; are not initialized and you're attempting to use it.
to solve this.
Change the for loop condition to for(i; i< 20; i++). Better to use a preprocessor construct like #define SIZ 20 and then make use of it accross your code to make it consistent and robust.
Initialize your local variables. max should be INT_MIN, and min can be INT_MAX. (see limits.h for reference).
To clarify more on point 2, max and min are automatic local variables, and in case not initialized explicitly, it contains indeterminate values.
C11, chapter §6.7.9,
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.
and then, directly from the Aneex J, §J.2, Undefined behaviour,
The value of an object with automatic storage duration is used while it is
indeterminate.
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
min and max are not initialized here. Make sure to set your compiler warnings at the highest level, so you get a warning message when you forget to initialize variables.
for(i;i<=sizeof(marks);i ++){
This doesn't make sense. Replace sizeof(marks) with the number of times you want to loop, and use < instead of <=.
For example:
const int num_marks = 20; // or use #define
int marks[num_marks];
for(i = 0; i < num_marks; i++) {}

For loop in C is looping more times than it should. Why? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here's the offending code:
int i, y, total = 0;
printf("%d\n", i);
for (i=0;i<2;i++) {
printf("why\n");
}
And the function it's included in:
void getStats(int month, const struct DailyData yearData[], int sz, struct MonthlyStatistic* monthly){
// based off monthly stats, function finds min and max temp (float), average temp and the total precipitation
int i, y, total = 0;
printf("%d\n", i);
for (i=0;i<2;i++) {
printf("why\n");
//printf("\n%d %d %d ", yearData[i].month, yearData[i].day, yearData[i].year);
//draw(symbolToDraw(yearData[i].condition, aver),20);
}
float max = 0, min = 0, averaged = 0, prec = 0;
//counts number of days in month
for (y = 0; y < 366; y++) {
if (yearData[y].month == month) {
total++;
}
}
//loop through year, assign data to variables if given row's month matches int month parameter
for (i=1;i<=365;i++) {
if (yearData[i].month == month) {
if (yearData[i].high > max) {
max = yearData[i].high;
}
if (yearData[i].low < min) {
min = yearData[i].low;
}
//printf("high: %f, low: %f\n", yearData[i].high, yearData[i].low);
averaged = average(yearData[i].high, yearData[i].low);
prec += yearData[i].precipitation;
}
}
monthly[month].averageTemperature = averaged;
monthly[month].maxTemperature = max;
monthly[month].minTemperature = min;
monthly[month].totalPrecipitation = prec;
return;
}
This code seems normal to me, however when I incorportate that loop in that function it has the following output:
From the look of things, when the loop exits the compiler goes backwards (if that's even possible?) and goes through the loop PLUS the print statement before it for a definate amount of times. How on earth could this sort of thing even happen? Is there something obvious I'm missing here or is this bug a lot more devious?
If, based on your question title, your question is why why is being printed more than twice, that's easy. The for loop is only running twice in the code you've posted, as evidenced by the fact it prints an integer between each set in your output.
Since that integer is likely to be the the printing of (the uninitialised) i variable, the most likely explanation is that you're calling getStats() more than once (probably in a loop).
However, based on your comment:
From the look of things, when the loop exits the compiler goes backwards (if that's even possible?) and goes through the loop PLUS the print statement before it for a definite amount of times.
it may be that your question is why it seems to be printing it in reverse order (two why lines then the number).
That's an artefact of your scrollback buffer in the window. Were you to have an extra line in the buffer, you would no doubt see another integer above the line you currently understand to be the first. I'd suggest looking at the end of the output and you'll no doubt see two why rather than an integer.

C Finding Maximum and Minimum value? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In Case of Finding Maximum and minimum Value in Array. We intialize max =0 or max=temp[0];
But in case of Minimum value we doesn't require to initialize min =0 or min=temp[0]... Why?
max = temp[0] acts as reference point. You start comparing each element with this and if any element is greater than this, max value will be updated to that one. similarly min = temp[0] is also valid, but now algorithm will be changed and you need to compare each element if anyone is smaller than this if yes then min will be updated to that.
You always need to initialise variables in C before accessing them; it's undefined behaviour not to. The best thing to do, is, having checked the array length is not zero, is to initialise min / max to the zeroth element. Then loop from the first element.
First, you shouldn't initialize max with 0 in any case (for example, when finding maximum of array which contains all negative values if you initialize max with 0, result will always be 0).
Since for finding maximum (and minimum) you need to compare variable max (or min) with some other value, you need to initialize to temp[0] in any case to avoid comparing array elements with uninitialized variable.
I found the part of your code in another comment:
#include<stdio.h>
int main() {
int arr[3];
int i,max,min; max=min=0;
printf("Enter the value in Array \n");
for(i=1;i<=3;i++) {
scanf("%d",&arr[i]);
}
printf("\n Value of array \n");
for(i=1;i<=3;i++) { printf("%d \n",arr[i]); }
printf("\n Finding Maximum and minimum value \n");
for(i=1;i<=3;i++) {
if(arr[i]>max) max=arr[i];
if(arr[i]<min) min=arr[i];
}
printf("Max = %d \n Min = %d \n ",max,min);
getch();
}
There are few things that doesn't work:
for(i=1;i<=3;i++)
In C, indexing starts from 0, so the valid array elements are arr[0], arr[1] and arr[2], so that for loop should be
for(i = 0; i < 3; i++)
Ok, now imagine that you have in your array elements 10, 5 and 7.
You're setting min value to 0:
max=min=0;
And now you are iterating over this loop:
for(i=0;i<3;i++) {
//...
if(arr[i]<min) min=arr[i];
}
Is 10 < 0? No, it's not.
Is 5 < 0? No, it's not.
Is 7 < 0? No, it's not.
So you see, the min will never change.
To avoid this, just set it to the first element after reading the array:
for(i= 0;i < 3;i++) {
scanf("%d",&arr[i]);
}
min = max = arr[0];
Now, let's repeat our loop:
for(i=0;i<3;i++) {
//...
if(arr[i]<min) min=arr[i];
}
Is 10 < 10? No, it's not.
Is 5 < 10? Yes, it is! Set the min to the 5
Is 7 < 5? No, it's not.
Now the min is 5.
Same issue you have in your existing code with max. Imagine you enter -4, -55 and -20 for elements - max would always stay 0.

Resources