I'm trying to create 2 dynamic arrays from the user input but the compiler is throwing a stack smashing array. This is my code:
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#define NUMS 3
// Put your code below:
int main() {
int high, low;
int high_temp[3];
int low_temp[3];
int total_temp = 0;
double median = 0;
printf("---=== IPC Temperature Analyzer ===---\n");
for (int i = 1; i <= NUMS; i++) {
printf("Enter the high value for day %d: ", i);
scanf("%d/n", &high);
printf("Enter the low value for day %d: ", i);
scanf("%d/n", &low);
if(!((high > low && high < 41) && (low < high && low > -41))) {
printf("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low");
i = i - 1;
}else{
high_temp[i] = i;
low_temp[i] = i;
}
}
for (int i = 0; i < sizeof(high_temp); i++){
//total_temp = total_temp + high_temp[i] + low_temp[i];
printf("The high value: %d", high_temp[i]);
printf("The low value: %d", low_temp[i]);
printf("-----");
}
}
And this is the output. The error happens when I'm trying to print out the elements in each array. I'm doing this to see if any of the illegal values creeped into the array. I'm suppose to take their medians afterwards.
---=== IPC Temperature Analyzer ===---
Enter the high value for day 1: 8
Enter the low value for day 1: -2
Enter the high value for day 2: 41
Enter the low value for day 2: -4
Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low
Enter the high value for day 2: 9
Enter the low value for day 2: -4
Enter the high value for day 3: 5
Enter the low value for day 3: 11
Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low
Enter the high value for day 3: 11
Enter the low value for day 3: 5
*** stack smashing detected ***: terminated
There are two major problems in your code, one in each for loop.
In the first, you need to remember that, in C, array indexes run from zero through to n - 1 (where n is the size of the array). So, the code:
for (int i = 1; i <= NUMS; i++) {
//...
should be replaced with this:
for (int i = 0; i < NUMS; i++) { // Note that NUMS = 3 and high_temp[3] is out-of-bounds
//...
The second for loop has a different error. Here, you are correctly running from zero to the n - 1 value, but you are miscalculating the n. So, instead of sizeof(high_temp) (which will give you the total size of the integer array) you need to divide that value by the size of one element (conventionally, use the first). So, use this, instead:
for (size_t i = 0; i < sizeof(high_temp)/sizeof(high_temp[0]); i++){
//...
(I've changed the type from int to size_t as this is what the sizeof operator returns; it is generally an unsigned int or unsigned long, or some such.)
EDIT: In the first loop, with the modifications I have suggested, you can 'restore' the correct number in the printed questions by simply adding 1 to the value of i that is printed. So, like this:
printf("Enter the high value for day %d: ", i + 1);
EDIT2:
There is also an issue regarding the values you assign in the first loop. You are doing this:
}else{
high_temp[i] = i;
low_temp[i] = i;
}
but the values you actually want to assign have been read into the high and low variables a few lines earlier. So, use this, instead:
} else {
high_temp[i] = high;
low_temp[i] = low;
}
There are a few problems with the code.
Your first for loop is wrong. The index should start at 0 and end before NUMS like this:
for (int i = 0; i < NUMS; i++)
This way the loop will go from from 0 to 2, since array indices start at 0 and your high_temp and low_temp arrays can only store 3 values. The way you have it written it will try to write to high_temp[3] and low_temp[3] which are not valid.
The upper bound of your second loop is wrong. sizeof(high_temp) doesn't do what you think it does; it returns 12 not 3, so in your second loop you're trying to access elements outside the bounds of the array. In general you would use sizeof(high_temp) / sizeof(high_temp[0]) but in this case you have already have NUMS so use that.
Related
I'm trying to solve a question to find the lowest and highest numbers in an array in C Language. I tried swapping the numbers that are close to each other to align the numbers from small(left) to big(right).
For example, if the array is 20, 10, 35, 30, 7, first compare 20 and 10, if 20 is larger than 10, swap the numbers to 10, 20. then compare 20 and 35, 20 is smaller than 35, so go on. then compare 35 and 30, 35 is bigger than 30, swap numbers to 30, 35. then compare 35 and 7, 35 is bigger than 7, swap numbers to 7, 35.
Did these 'swappings' again 3 more times to align the numbers perfectly.
After I've done the swappings, I just printed the first array number and the last array number, but the numbers aren't correct, and it looks like the numbers have shifted by 1. For example, if I align the above array, it is 7[0], 10[1], 20[2], 30[3], 35[4]. (marked the indices by []) So, when I print the indice[0], and indice[4], I expected the numbers to show 7 and 35.
But in fact I have to print indice[1], and indice[5] to get the numbers 7 and 35 to be printed. The numbers seem to have shifted by 1..
I really want to know why the numbers have shifted by 1 in the array.
Thank you for reviewing the question.
I'll also post the original question that I'm trying to solve.
"Q. Input the number N first to decide how much numbers to enter, then input the N-numbers. Print the lowest and highest number in the N-numbers you have input."
And here's my code:
#include<stdio.h>
#pragma warning(disable:4996)
int main(void)
{
int input, i, j, temp, k;
int value[100] = { 0 };
scanf("%d", &input);
for (i = 0; i < input; i++)
{
scanf("%d", &value[i]);
}
for (k = 0; k < input; k++)
{
for (j = 0; j < input; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j + 1];
value[j + 1] = value[j];
value[j] = temp;
}
}
}
printf("%d %d\n", value[0], value[input-1]);
return 0;
}
Because you're iterating over the whole array, value[j+1] walks off the end of the user's input. Since value was initialized 0 to, temp = value[j + 1] will be 0. So 0 will always be your min (unless the user enters negatives).
Instead, iterate only up to j < input - 1.
I'm trying to solve a question to find the lowest and highest numbers in an array in C Language.
You don't need to sort the array, you can do this in a single pass.
// Initialize min and max to be the first value.
int min = value[0];
int max = value[0];
// Then loop through the rest of the array checking if each value is
// smaller than min and/or larger than max.
for (i = 1; i < input; i++) {
if( value[i] < min ) {
min = value[i];
}
if( value[i] > max ) {
max = value[i];
}
}
printf("min: %d, max: %d\n", min, max);
Note: It's not necessary to declare all your variables up front. You can declare them as you need them. And you don't need different iterators for each loop, you can reuse i as I have above.
I'm a newbie and i'm currently making a program that asks the user a number and if the number is a prime it gets stored in a vector, if the vector isn't completed the code doesn't stop. The only problem is that it stores multiples of 5, like 15, 25, 35, etc in it. How can i make it stop storing these multiples of 5? Here is the code:
#include <stdio.h>
int main()
{
int primes[5], num, i, count = 0, x = 0;
do
{
printf ("Type a number: ");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
count++;
}
}
if (count = 2)
{
primes[x] = num;
x++;
}
}
while (x < 5);
for (x = 0; x < 5; x++)
{
printf("%d ", primes[x]);
}
}
= is the assignment operator, not the equality check operator. You should use == to check if the count is 2:
if (count = 2)
You write
for (i = 1; i<= num; i++)
a prime number is a number that is divisible only by one and itself, your primality test divides your number by all numbers (includind 1 and num itself) so every number (prime or not) will probe to be compound.
Your primality test must start at 2 and end at most at num - 1 to avoid dividing the number by one and by itself (all numbers are divisible by themselves and by one) as in
for (i = 2; i < num; i++)
this should solve your problem... but it will be very inefficient, as you are dividing by all the even numbers, and it is not necessary to divide it by all the even numbers (except for 2 itself) Also, you can stop at a number that is below or equal to sqrt(num), rounded down to the previous integer, because if the number has a factor above that number, for sure you have already found a factor below it (and both multiply pairwise to give you the number).
Also, there's a problem here:
if (count = 2)
This is a valid C statement, but it most probably don't do what you intend, as the = operator is the Assignment Operator, and not the logical equal operator (which is spelled ==) You need to change, because as shown, you are assigning count the value 2, and this is always true, by definition of the assignment operator, if you assign something different than zero, it will result in a true result, so your if will execute allways the body of its true part.
Anyway, many variables it's not clear what you are using them for, (count is one of these) as you assign, increment it, but you don't use its value anywhere (except the if statement above, and in a wrong way)
Hey there i'm currently developing a lotto type game and one of my requirements is to record the frequency of the numbers inputted by the user and then display them if the users wishes to see them. The program also must be modular hence the functions.
My problem is that i can't seem to figure out how to keep track of the numbers I tried numerous things and this is the closest I've gotten...
void num_free(int *picked_nums)
{
static int elements[MAX] = { 0 };
int i;
for (i = 0; i < MAX; i++)
if (*(picked_nums + i) == i)
{
elements[i]++;
}
for (i = 0; i < MAX; i++)
{
if (elements[i] != 0)
{
printf("\nThe amount of times you chose %d is %d", i, elements[i]);
}
}
printf("\nEnter any key to return to main menu");
getchar();
}
The output of this every time i run it no matter the input is
"The amount of times you chose 11 is 1"
I'm really clueless as to what to do next so any and all help would be appreciated. Thanks in advance!
EDIT: The user can play multiple rounds and thats how the frequency of the numbers can add up.
I think the main problem in your code is here:
if (*(picked_nums + i) == i)
{
elements[i]++;
}
you actually check if the i-th number the user chose equals to i. That means that increment is done only in that case - which is not what you want (if I got you right).
I think you should give up the if statement, and, assuming that the user chooses only non-negative numbers (and that the elements array is properly zeroed at the beginning), do this:
elements[picked_nums[i]]++;
Namely, you increment the array cell matching the chosen number (and the i is only the index you use to iterate the picked_num array).
The problem is how you count and store the numbers:
if (*(picked_nums + i) == i)
{
elements[i]++;
}
Your i is moving and at the same time the element chosen from picked_nums is moving. This loop will not count or store properly.
The provided solution assumes that picked numbers are stored in the numbers array. I assumed that numbers are in 1 to 64 range. You can adjust program to your needs. Test provided:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void num_free(int picked_nums[], int size )
{
static int elements[65] = { 0 }; // numbers can be from 1 to 64 range
int i;
for (int j = 0; j < size; j++)
{
int n = picked_nums[j];
for (i = 1; i < 65; i++) // numbers can be from 1 to 64 range
{
if ( n == i)
{
elements[i] = elements[i]+1;
}
}
}
for (i = 0; i < 65; i++)
{
if (elements[i] != 0)
{
printf("\nThe amount of times you chose %d is %d", i, elements[i]);
}
}
// printf("\nEnter any key to return to main menu");
// getchar();
}
// array of entered numbers:
int numbers[] = { 2, 2, 2, 40, 7, 7, 8, 9, 40 };
int main(void) {
num_free(numbers, 9); // call with sizeof numbers
return 0;
}
Test:
The amount of times you chose 2 is 3
The amount of times you chose 7 is 2
The amount of times you chose 8 is 1
The amount of times you chose 9 is 1
The amount of times you chose 40 is 2
I am writing a C program to get Fibonacci number, the user needs to put the first 2 numbers and the sequence starts from there. Here is my code:
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int i, input[MAX_SIZE];
printf("please Enter first 2 digit of the Sequence\n");
scanf("%d, %d" , &input[0], &input[1]);
for (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
return 0;
}
But when i run the code with a input 2 and 3, I get a output like this 1499141456, which is clearly not the sequence. please help.
When you exit from the loop i is equal to MAX_SIZE
printf("%d\n", input[i]);
you are printing a value outside of the bounds of the array (input[MAX_SIZE]).
It's because the result in your code is bigger that the maximum value an int can handle
Live example here!
From Wikipedia
The number 2,147,483,647 (or hexadecimal 7FFF,FFFF16) is the maximum
positive value for a 32-bit signed binary integer in computing. It is
therefore the maximum value for variables declared as integers (e.g.,
as int) in many programming languages, and the maximum possible score,
money, etc. for many video games.
Here's where it goes wrong
[...]
433494437 + 701408733 = 1134903170
701408733 + 1134903170 = 1836311903
1134903170 + 1836311903 = -1323752223
put print statement inside for loop braces.
or (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
I wrote this program per my professor's instruction. Turns out he wanted us to use a SINGLE do-while loop. While I did technically do that... this won't fly. I can't figure out how to do it without using a for-loop or at least another loop of some other type. He said it could use continue or break statements--but that it might not be necessary.
I would appreciate not just re-writing my code--while this is handy, I don't learn from it well.
I appreciate any and all help.
int main() {
int max, x, n = 2; //init variables
//start n at 2 because 1 isn't prime ever
//asks user for max value
printf("Enter max number: ");
scanf("%i", &max);
/*prints prime numbers while the max value
is greater than the number being checked*/
do {
x = 0; //using x as a flag
for (int i = 2; i <= (n / 2); i++) {
if ((n % i) == 0) {
x = 1;
break;
}
}
if (x == 0) //if n is prime, print it!
printf("%i\n", n);
n++; //increase number to check for prime-ness
} while (n < max);
return 0;
}
This is definitely doable. The trick is to have a test variable, and each iteration through your while loop, check the test variable against your current number. Always start the test variable at 2 (every natural number > 0 is divisible by 1)
Cases to consider:
Our current number is divisible by the test variable -- number is NOT prime, increase the current number and reset the test variable.
Our test variable is greater than the square root of the current number. By definition, it CANNOT divide the current number, so the current number has to be prime (we have tried all numbers lower than the square root of the current number and none of them divide it). Increase the current number and reset the test variable.
Lastly, if either above case isn't true, we have to try the next number higher. Increment the test variable.
I have not provided the code as you asked to not have it re-written, but can provide if you would like.
EDIT
#include <stdio.h>
#include <math.h>
int main(void)
{
int max = 20;
int current = 4;
int checker = 2;
do{
if(checker > sqrt((double)current))
{
checker = 2;
printf("%d is prime\n",current);
current++;
}
else if(current % checker == 0)
{
checker = 2;
printf("%d is NOT prime\n",current);
current++;
}
else
checker++;
}while(current < max);
}
Output:
4 is NOT prime
5 is prime
6 is NOT prime
7 is prime
8 is NOT prime
9 is NOT prime
10 is NOT prime
11 is prime
12 is NOT prime
13 is prime
14 is NOT prime
15 is NOT prime
16 is NOT prime
17 is prime
18 is NOT prime
19 is prime
I won't give you the exact code, but two pointers that should help you:
First, a for loop can be written as a while loop (and, vice versa)
for (int i=0; i< 100; ++i)
...
would become:
int i=0;
while (i < 100)
{
...
++i;
}
Second, two nested loops can become a single one, in any number of ways:
for (int i=0; i< 100; ++i)
for (int j=0; j< 100; ++j)
...
Becomes
for (int z=0; z< 100*100; ++z)
{
i = z / 100;
j = z % 100;
}
The above shows two for loops, but you can perform similar transforms on other loops.
Think Eratosthenes sieve. In this method we strike composite numbers out of a table, so that in the end only primes remain. For simplicity, the table contains only odd numbers. You start pointing at 3, which is a prime. Strike out 3*3, 3*5... Finish your run over the table (it's finite), point at 5. It's not striked out, thus a prime. Strike out 15, 25... check 7, prime, strike 21, 35... check 9, already striked out, move on to 11...
Questions:
You have just checked a number, what is the next number to check?
How do you know you've ran out of numbers to check?
Write down answers to these questions, and you have a one-loop prime-finding algorithm.