When printing Arrays in C some numbers print as 0.00 - c

This code asks for 10 simple values to create an array and then prints them. The scanf is correct, you can enter the 10 values normally.
The problem is, when printing, that every single value from 1 to 10 is printed as expected but the 7 & 8 values are printed as 0.00. I thought it could be that the for loop is not running correctly but the other numbers are printed just fine.
Does anyone know whats the problem? Why just 7 & 8? Can I fix it using the same structure?
Appreciate the help, I'm new to this. This is what I have:
#include<stdio.h>
int main()
{
int index;
int size = 10;
float values[index];
for (index=0; index < size; index++)
{
printf("\nEnter value[%1d]: ",index+1);
scanf("%f",&values[index]);
}
for(index=0; index < size; index++)
{
printf("\nvalue[%1d]= ", index+1);
printf("%.2f", values[index]);
}
return 0;
}

Just a simple mix up...
When you create float values[index]; index is uninitialized, which results in undefined behavior.
Change this:
int index;
int size = 10;
float values[index];
^
To this:
int index;
int size = 10;
float values[size];
^

Related

How to print the sum of a passing a int array as a parameter

#include <stdio.h>
int sumofArrayNum(int numList[]);
int main(){
int result,numList[]={23,32,54,23,54,32,3,35};
result = sumofArrayNum(numList);
printf("sum= %d", result);
return 0;
}
int sumofArrayNum(int numList[]){
int sum = 0;
for(int i = 0; i < 10; ++i){
sum += numList[i];
}
return sum;
}
Output is different each time I build and run it.
E.g. output is sum = 1032918821
Expected output I would like is sum = 256
Parameters like int numList[] is the same as int* numList, compiler will not know elements count of it if it was not explicitly defined. By the way, int numList[8] is also the same as int* numList. C language does not check the range of array.
There are some ways to get and check the array size.
size/count parameter
int sumofArrayNum(int numList[], int listSize){
int sum = 0;
for(int i = 0; i < listSize; ++i){
sum += numList[i];
}
return sum;
}
Here listSize should be the count of elements.
And you can use macro to hide the count parameter:
#define sumofArray(array) sumofArrayNum((array), sizeof(array)/sizeof(*array))
point to the whole array
int sumofArrayNum(int (*numList)[8]){
int sum = 0;
for(int i = 0; i < sizeof(*numList)/sizeof(**numList); ++i){
sum += (*numList)[i];
}
return sum;
}
Call it by sending pointer of array:
result = sumofArrayNum(&numList);
Compiler(such as gcc) can do a weak check for this: give a warning if you send an array which are not int (*)[8].
Note that you have to ensure validity of array, and array size must be constant.
Besides,
Output is different each time I build and run it.
It is because only 8 elements has been defined, index range is 0〜7. numList[8] and numList[9] is undefined, mean any value is possible. Maybe used, changed by other process, random and dangerous.
In numlist there are 8 element that means for loop must execute code 8 times.
Your code must be:
for(int i = 0; i < 8; ++i)
{
sum += numList[i];
}
This code iterate until i=7, when i=8 it will end the loop.
Information on for loop

Double arrays in C

Im in the process of learning C and the basis of the class is C primer plus(6th edition). We use Eclipse as an IDE.
For an project we have to create to arrays. One array that takes numbers in a loop and another array that display the cumulative value. So if array 1 has values 1, 5 and 3(out of 10 inputs total) then the resulting input in array 2 should be 9(on the 3th input because of the 3 inputs in array 1).
Im having trouble getting started the right way - anyone here has ideas how I could proceed?
So far I have this for starters but forgive me for it it very weak:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void doublearrays (double usernumber);
int main(void)
{
double usernumbers = 0.0;
int loop1 = 1;
while(loop1)
{
printf("Type numbers as doubles. \n");
fflush(stdout);
loop1 = scanf("%lf", &usernumber);
if(loop1)
{
doublearrays(usernumber);
}
}
return 0;
}
All the text in a homework assignment shall be read:
For a project we have to create two arrays... 10 inputs total...
Why on earth do not you declare them?... You already have defined SIZE so
double usernumbers[SIZE];
double cumulnumbers[SIZE];
Next do yourself a favour and handle one problem at a time:
One array that takes numbers in a loop...
Ok, so write a loop up to 10 reading floats directly into the array and note how many numbers were received
int n;
for(n=0; n<SIZE; n++) {
if (scanf("%lf", &usernumbers[n]) != 1) break;
}
// ok we now have n number in the first array
Let us go on
and another array that display the cumulative value.
Ok cumul is initially 0. and is incremented on each value from the first array:
double cumul = 0.;
for(int i=0; i<n; i++) {
cumul += usernumbers[i];
cumulnumbers[i] = cumul;
}
(your current code isn't what you need... delete it and then...)
anyone here has ideas how I could proceed?
Well the first step would be to actually define some arrays.
double input[SIZE];
double cum[SIZE];
The next step would be a loop to read input.
for (int i = 0; i < SIZE; ++i)
{
if (scanf("%lf", &input[i]) != 1)
{
// Input error - add error handling - or just exit
exit(1);
}
}
The next step is to add code for calculating the the cumulative value.
I'll leave that for you as an exercise.
The last step is to print the array which I also will leave to you as an exercise.
The straight forward way of doing this, which would also use two arrays and a loop construct would be to create something like this.. I've changed the doubles to integers. (and i am also ignoring any errors from scanf()).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
static void
print_array(int *arr, const char *arr_name)
{
int i;
printf("%s = [");
for (i = 0; i < SIZE; i++)
printf("%d%s", arr[i], i < SIZE -1 ? ",":"");
printf("]\n");
}
int main(int argc, char **argv)
{
int i;
int input[SIZE];
int cumsum[SIZE];
for (i = 0; i < SIZE; i++)
{
int _input;
printf("Give me numbers!\n");
fflush(stdout);
scanf("%d", &_input); /* assuming integer */
input[i] = _input;
cumsum[i] = i > 0 ? cumsum[i-1] + _input : _input;
}
print_array(input, "input");
print_array(cumsum, "cumulative");
return 0;
}
or If you'd like to play around with pointers and have a bit more compact version.. perhaps this could be something to study to help you understand pointers, it does the same thing as my code above
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
static int data[SIZE*2];
int main(int argc, char *argv[])
{
int *input_p = &data[0];
int *cumsum_p = &data[0] + SIZE;
for (; input_p != &data[0] + SIZE; input_p++, cumsum_p++)
{
printf("Give me numbers!\n");
scanf("%d", input_p);
*cumsum_p = input_p == &data[0] ? *input_p : *(cumsum_p-1) + *input_p;
}
}

Generating a random code in c

I'm trying to generate a random 10-digit code, but even though I use the absolute value of every number in the code, it still sometimes prints a negative value
#include <stdio.h>
int main()
{
int i;
int r;
int barcode[11];
srand(time(NULL));
for(i=0;i <= 10;i++){
r = rand() % 10;
barcode[i] = abs(r);
}
printf("%d",barcode);
return 0;
}
Because you are actually printing the address of an integer array, not a string.
This line:
printf("%d",barcode);
Basically prints the address of barcode as a signed integer instead of the contents of barcode.
You of course could do this:
printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);
But perhaps a better way is to generate a string of characters instead of an array of integers. Quick mod to your code is to add to '0' to each random value in each interation of the loop and append to a char array.
int main()
{
int i;
int r;
char barcode[11]; // array of chars instead of ints
srand(time(NULL));
for(i=0; i < 10; i++) // loop 10 times, not 11
{
r = rand() % 10;
barcode[i] = '0' + r; // convert the value of r to a printable char
}
barcode[10] = '\0'; // null terminate your string
printf("%s\n",barcode);
return 0;
}
The above will generate a 10 digit code, with a small possibility of the first number being a leading zero. If that's not what you want, that's a simple bug fix. (Which I'll leave up to you...)

Passing an array to a pointer

I'm trying to learn C Language using pointers and arrays etc... but my code won't work. Whats is wrong with this code?
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
int main(){
int *number = 0;
int i = 0;
int *random = 0;
int randomTry[100];
int *getRandomTry = 0;
int randomGenerator[100];
int *getRandomGenerator = 0;
srand (time(NULL));
*getRandomTry = randomTry[100];
*getRandomGenerator = randomGenerator[100];
do{
*random = rand() % 10;
getRandomGenerator = random;
printf("Choosing a number:\n\r");
for(i = 0; i < 30; i++){
printf("*");
Sleep(50);
}
printf("\n\r\n\rWell done, your time.");
printf("\n\r------------------------------");
printf("\n\rPick a number ( 0 to 10): ");
scanf("%d", number);
getRandomTry = number;
if(*number > 10){
printf("\n\rRemember, number only from (0 to 10)\n\r");
}
else{
if(number == random){
printf("\n\rYou choose right!");
printf("You entered theses numbers till the right answer");
for(i = 0; i < randomTry[i]; i++){
printf("%i", getRandomTry);
}
}
else{
printf("\n\rYou choose wrong, number: %d - random: %d\n\r", number, random);
Sleep(700);
system("cls");
}
}
}while(number != random);
getch();
return 0;
}
When i compile the program stop working, no warnings or comments show in console.
I'm using the notepad++ with MinGw to compile this code.
Assigning a value to a NULL pointer is undefined behaviour, such as (in your code).
int *getRandomTry = 0;
*getRandomTry = randomTry[100];
gives undefined behaviour on two counts. The second statement tries to retrieve the value of randomTry[100], which doesn't exist (since array indexing starts at zero, and randomTry only has 100 elements). Second, it tries to store that value into a location addressed by the NULL pointer.
With undefined behaviour, anything can happen. Program crashes are pretty common, but not the only possible result.
So you need to understand how array indexing works (it starts at zero, not one). And you need to ensure all pointers point at something valid before trying to set or retrieve values via the pointer.
For example;
int x = 5;
int *getRandomTry = &x;
*getRandomTry = 42; // will change x
The following is a correct declaration of a pointer to an integer, with initial value zero:
int *random = 0;
The following statement will try to place the result of the calculation to the address in memory where the pointer 'random' is pointing:
*random = rand() % 10;
Since 'random' was assigned the value of 0, it is pointing at memory location zero, and the second statement will result in 'undefined behavior', meaning that what happens next in your program is not easily predictable. In practice, it will most likely crash in one way or another, since you cannot write to memory location 0.
if the code was like this:
int random = 0;
...
random = rand() % 10;
then everything would work fine. It would also work if code was like this:
int random_variable;
int *random = 0;
...
random = &random_variable;
...
*random = rand() % 10;
In this last case, 'random_variable' would end up with the result of the calculation.
Hope this helps.

Segmentation Fault 11 with recursive function in C

I keep receiving a Segmentation Fault 11 for the following code. I believe it has something to do with recursion but I'm not entirely sure how. The method should take in an array, skip the odd values, and keep repeating until it has an array with only value left and returns that value.
Thanks!
#include <stdio.h>
int callTable(int table[], int size)
{
int i = 0;
int j = 0;
int cHeight = size / 2;
int cTable[cHeight];
while (i < size)
{
if (table[i] % 2 == 0)
{
cTable[j] = table[i];
j++;
}
i++;
}
if (size > 1)
return callTable(cTable, cHeight);
else
return cTable[0];
}
int main()
{
int tPass[100];
int i, answer;
for (i = 0; i < 100; i++)
tPass[i] = i + 1;
answer = callTable(tPass, sizeof(tPass) / sizeof(tPass[0]));
printf("%d\n", answer);
}
Do you want to skip the odd values or the odd indexes? You are currently skipping the odd values, so after you call callTable once, there are only even values left. Then, on the second call, you try to use an array of half the size to store the even values (which are all of them), so you try to store the entire array on another with half the size.
If you intended to skip the odd indexes, then change this line:
if (table[i]%2==0)
for this one:
if (i%2==0)
That runs fine and returns 1 (which is the number with index 0).

Resources