Extra values when printing an array(converting from %s to %c) - c

I am trying to create a simple program where the user will have to enter a series of numbers and the program should output the square and the cube of the given number. However, when I try to use an array, it prints some random numbers I didn't even input. Any help would be appreciated to eliminate the unecessary input. Thank you.
#include <stdio.h>
int main()
{
char *value;
value = malloc(sizeof(20));
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}

You are taking input in char and doing arithmetic operations on it.
Use this code, it will give you correct output.
#include <stdio.h>
int main()
{
int *value;
value = (int *)malloc(20 * sizeof(int));
//float answer;
int x;
int y;
for(x=0; x < 20; x++)
{
scanf("%d" , value + i);
}
for(x=0; x < 20; x++)
{
y = value[x];
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}

The problem is with your malloc statement.
sizeof is used to determine the parameter size - in your case a hard-coded integer. The generated array is of size 4, which is exactly sizeof(20) instead of 20 integers which is 20*sizeof(int). It will be best to allocate the array statically if you know what size you need, see code below:
#include <stdio.h>
int main()
{
// This line sets value to an array of 20 ints
int value[20];
// Another, less favorable option, but still works:
// char *value = malloc(20 * sizeof(int))
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}

The expression sizeof(20) returns the size of an int (the literal 20 is an int), which is typically only 4 bytes. In other words, you are only allocating a single integer for your array. All access outside of that single integer will result in undefined behavior.
You need to allocate sizeof(int) times the number of elements, if you want to dynamically allocate the memory. Or (which I recommend) use a normal array:
int value[20];
There is also another problem, in that you only read a single value from the user. You should probably be reading in the loop too.
But if you read in the loop, then there is really no need to even have an array to begin with, only a single int Variable which you read into, and then print its value as squared and cubed.
So the code could be simplified as
#include <stdio.h>
int main(void)
{
int value;
for (unsigned i = 0; i < 20 && scanf("%d", &value) == 1; ++i)
{
printf("The square of %d is: %d\n", value, value * value);
printf("The cube of %d is: %d\n", value, value * value * value);
}
return 0;
}
You also need to be careful of overflows when multiplying.

Related

calculating the sum of input numbers in c language

I want to calculate the sum of input numbers using pointer concept in c language.But when i compile the given below program correct value for sum does not appear. help me to find the mistake i have done in the below program.
#include<stdio.h>
void main()
{
int g , *p;
int sum = 0;
int x=1;
for(int i=1; i<3; i++ )
{
scanf("%d ", &g);
}
p = &g;
while( x < 3){
sum = sum + *p;
p++;
x++;
}
printf("\n sum = %d ",sum);
}
Your g is only one integer so:
Each time you call scanf("%d ", &g);, you will overwrite the previous value.
When you increment the pointer in p++;, that pointer will no longer be valid. (Where do you think it will point to?)
If you want to store three different values in g, you need to make it an array of integers.
To do this, make the following changes to your code:
int g[3] , *p; // "g" can now store three different values
int x=0; // Later on - counting from 0 thru 2 in the "while" loop
//...
for (int i=0; i<3; i++) // NOTE: Arrays begin at "0" in C!
{
scanf("%d ", &g[i]); // Store to the element indexed by "i"
}
//...
p = g; // For arrays, don't need the & operator: this will give address of first element
You can store only one number in g.
Therefore, p++; here will make p point at an invalid place.
You should allocate an array to store all input values.
Also note that you should use standard int main(void) in hosted environment instead of void main(), which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.
#include<stdio.h>
int main(void)
{
int g[3] , *p;
int sum = 0;
int x=1;
for(int i=1; i<3; i++ )
{
scanf("%d ", &g[i]);
}
p = &g[1];
while( x < 3){
sum = sum + *p;
p++;
x++;
}
printf("\n sum = %d ",sum);
}

How do I create an array with undefined length? (In C)

I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).

How to create an Empty Array to store values calculated from the given from program in C

I am having difficulties initializing an array to how values given from a for loop, I want to discard the prime numbers calculated and then keep the non prime numbers in an array, which the size of the array must be unknown from the beginning. I must then call collect the numbers from the array and then apply the Carmichael equation to them to find Carmichael numbers.
Applying the equation to the values in the array is what I am finding difficult as well.
This is my code:
int main(int argc, char **argv){
int a ,b;
int notPrime[] = {};
printf("Type in two non negative intergers: \n");
scanf("%d" "%d", &a , &b);
int i=a , k=0 ,count=0, j, p, m;
for (i < b;){ //from the integers given b must be the larger of the two
if (i==0 || i==1) { //to calculte the prime numbers
notPrime[k]=i;
}else{
for( j=2;j<i;j++){
if(i%j==0){
break;
}else{
notPrime[k]=i;
}
}
}
i++;
k++;
}
p=0;
if (p<=k){
for (m=1;m<notPrime[p];m++){
if((pow(m,notPrime[p])-m)%notPrime[p]==0){ //use of the values in the array and use of the carmichael equation
count=count+1;
}
if(count==notPrime[p]-1){
Printf( "%d \n", &notPrime[p]) ;
}
}
}
return 0;
}
i have errors on for (i < b;){, if((pow(m,notPrime[p])-m)%notPrime[p]==0){ and finally the print statment Printf( "%d \n", &notPrime[p])
Please could I get a little help, just set me in the right direction and I will try to correct.
xRapture
for (i < b;){
This is not a valid syntax for for loop . You can write like this instead -
for (;i < b;){
And this -
if((pow(m,notPrime[p])-m)%notPrime[p]==0){ //
pow return double and notPrime[p] is int . % operator on double and int .
Explicitly cast result of pow to int.
Also this -
printf( "%d \n", &notPrime[p]) ;
^ this is not needed
don't pass address of int.
Edit -
You can declare your array as this after taking input a and b -
int notPrime[a] = {0}; // or size b as you desire

Formula throwing error 'called object is not a function'

I'm doing an exercise in C that has me inputting data into a struct and then manipulating it in a separate function. But when the program comes to the line where the actual math is being done, I get an error about a called object not being a function.
Here's the exact error:
p1s2.c:70:106: error: called object '(vectorArray + (sizetype)((unsigned int)i * 32u))->y * (vectorArray + (sizetype)((unsigned int)i * 32u))->y' is not a function
I'll apologize in advance for the code, this is a work-in-progress file so it isn't very clean.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Structure declaration.
struct vector {
double x; //X-coordinate for vector
double y; //Y-coordinate for vector
double z; //Z-Coordinate for vector
double length; //Length. Calculations will go here.
};
int howLong(struct vector *x);
int main(void)
{
int arraySize;
int i;
int vectorNum=1;
int retval; //Watch for counter in howLong.
int scanval; //Error checking for coordinates input (scanf statement)
printf("How many vectors would you like to calculate length for?\n");
scanf("%d", &arraySize);
//Allocate memory to struct.
struct vector *vectorArray = malloc(arraySize*sizeof(double));
printf("You will now enter the coordinates for %d vectors. \n", arraySize);
//Input loop.
for(i=0; i<=arraySize; i++){
printf("Please enter the X, Y, Z coordinates for vector %d. \n", vectorNum);
printf("Please separate the coordinates with spaces. \n");
int scanval; //Error checking: Scanval should be equal to three.
//scanf takes user input, converts to long float.
scanval=(scanf("%lf %lf %lf", &vectorArray[i].x, &vectorArray[i].y, &vectorArray[i].z));
if(scanval !=3) {
printf("You can't follow directions. That's too bad. \n");
exit(0);
}
//Print input back to user.
printf("Vector Number %d: %lf %lf %lf \n", vectorNum, vectorArray[i].x, vectorArray[i].y, vectorArray[i].z);
//Increment counters.
vectorNum++;
i++;
}
for(i=0; i<=arraySize; i++){
vectorArray[i].length=howLong(vectorArray);
i++;
}
}
Here's the external function howLong:
int howLong(struct vector *vectorArray)
{ //Function gets the struct and coordinate values, calculates length and writes to struct.
int i;
int vectorNum=1;
printf("Calculating vector length. \n");
//Math.
vectorArray[i].length = sqrt((vectorArray[i].x * vectorArray[i].x)+(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z));
//Error occurs on the line directly above this comment. ^^
printf("Length of Vector Number %d: %lf \n", vectorNum, vectorArray[i].length);
return vectorArray[i].length;
}
I don't get it. At first I thought it had to do with function names, but the error persisted after I changed the function name to howLong. Any ideas?
Well, here:
(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z)
is missing a plus sign, between the two () parts.
In function howLong
((vectorArray[i].x * vectorArray[i].x)+(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z));
^operator is missing

C array with structs

I am a very beginner at structs and barely understand what they are useful for. I have an assignment to create an array with space for 5 points. Every point will be entered by the user.
I don't understand how to use structs with arrays. I tried this but it doesn't work at all...
#include <stdio.h>
int main(void)
{
struct Input
{
int x;
int y;
};
struct Input arr[5];
for(int i=1; i <= 5; i++)
{
printf("Enter coordinates for point #%d (x,y): ", i);
scanf("%d,%d", &arr[i].x, &arr[i].y);
}
printf("\n\nYou entered:\n");
for(int i=1; i <= 5; i++)
{
printf("Point #%d: %d, %d\n", i, arr[i].x, arr[i].y);
}
getchar();
getchar();
return 0;
}
EDIT
I am trying to calculate the average of the x coordinations, but obs.avgX doesn't work like planned, the calculation always gets 0.
#include <stdio.h>
int main(void)
{
struct Observations
{
int x;
int y;
double avgX;
double avgY;
};
struct Observations arr[5];
struct Observations obs;
for(int i=0; i < 5; i++)
{
printf("Enter coordinates for point #%d (x,y): ", i +1);
scanf("%d, %d", &arr[i].x, &arr[i].y);
}
printf("\n\nYou entered:\n");
for(int i=0; i < 5; i++)
{
printf("Point #%d: %d, %d\n", i, arr[i].x, arr[i].y);
}
obs.avgX = arr[0].y + arr[1].y + arr[2].y + arr[3].y + arr[4].y / 5;
printf("Average of X: %d", obs.avgX);
getchar();
getchar();
return 0;
}
If you need to create an array of 5 points, first you have to define what a point is.
For example:
struct Point {
int x;
int y;
};
Then you have to define an array of 5 points:
struct Point array_of_points[5];
And you can use it like this:
array_of_points[0].x = 20;
array_of_points[0].y = 10;
// etc...
array_of_points[4].x = 3;
array_of_points[4].y = 8;
SirDarius gave a nice explanation about code.
You said
barely understand what they are useful for
In fact , you can consider , that structs are a kind of "data saver" where you can store DIFFERENT or MULTIPLE types of data .
For example , using arrays , you can not store both x and y coordinates at a cell (Multiple types of Data).
Moreover , if you want to store a Student's School Info , you may want to store , his unique ID (integer) ,his name (string) , his grade (integer) and the average of each lesson (float) (Different Data). Using structs you can easily store them that way :
struct Student {
int ID;
char * name;
int grade;
float average;
}
Hope that helped to understand ,the reason why structs are really useful :)
Braces are missing as below when computing the average,
obs.avgX = (arr[0].y + arr[1].y + arr[2].y + arr[3].y + arr[4].y) / 5;
Also to print a double type variable you should be using %f as the format specifier rather than %d.

Resources