I have to solve this problem: "Write a program that reads from the keyboard a sequence of 10 integers, and writes the same sequence in reverse order, dividing by 2 the even elements of the sequence."
I want to know the size of the array p to print it in the reverse order but when I try to get the size of array with "l = sizeof(p)/sizeof(p[0])" the for loop below doesn't works.
int main(){
int n,i;
int *p;
int l;
printf("How long the array? ");
scanf("%d",&n);
p = malloc(n*sizeof(int));
if(p != NULL){
for(i=0;i<n;i++){
printf("Insert number in index (%d) of array: ",i);
scanf("%d",p+i);
}
l = sizeof(p)/sizeof(p[0]);
for (i=n;i == 0;i--){
if(p[i] % 2 == 0){
printf("%d ",p[i]/2);
}
else{
printf("%d",p[i]);
}
}
}
else{
printf("ERROR!!");
}
return 0;
}
The return value of sizeof will be a size in bytes - not of the array, but the pointer, which is an integer in this case. What you want is the length. You have the length stored in n.
Your for-loop is a bit confusing. Try using n - 1 (the length of the array) in order to start the loop by accessing the last index value of the array. Also, the printf inside the else block doesn't space the output correctly. Try the following code:
for (i = n - 1; i >= 0; --i)
{
if (p[i] % 2 == 0)
{
printf("%d ", p[i] / 2);
}
else
{
printf("%d ", p[i]);
}
}
when I try to get the size of array with l = sizeof(p)/sizeof(p[0]) the for loop below doesn't works.
This fails as p is a pointer, not an array. The size of p is something like 4 or 8.
I want to know the size of the array p
p is not an array. Simply use the n as used in the allocation.
Related
Example: input: 420 50 -4
output: Numbers 3
Positive 2
Negative 1
and also for the same code:
input: 420 50 -4 7
output: Numbers 4
Positive 3
Negative 1
#include<stdio.h>
#define N 2
int main()
{
int a[N], i=0, n=0, k=0, z=0;
for(i=0; i<N; i++)
{
scanf("%d" , &a[i]);
if((a[i] >= -10000 && a[i] <= 10000 ))
n++;
if(a[i]>0)
k++;
if(a[i]<0)
z++;
}
printf("Numbers:%d \n", n);
printf("Positive:%d \n", k);
printf("Negative:%d \n", z);
return 0;
}
new issue
So the idea is this, I need my programm(mostly done by yano here) to only be able to load numbers ranging for -10000 to 10000 including border numbers, if other numbers would be loaded, the program should print the correct numbers, and ignore the incorrect (more like remove from array and replacing the element with the rest, which is correct, whilst reducing the total number of elements in the array)
example
input 140 -154161 20 30
output 140, 20, 30
Error: Input is outside interval!"
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10
void
printArray (const int *myArray, size_t numsEntered)
{
int i, c = 0, k = 0, z = 0, s=0, l=0, sum=0, max, min;
float pk, pz, ps, pl, prumer;
for (size_t i = 0; i < numsEntered; i++) //does math
{
sum = sum + myArray[i];
if (i)
printf (", ");
printf ("%i", myArray[i]);
if ((myArray[i] >= -10000 && myArray[i] <= 10000))
c++;
if (myArray[i] > 0)
k++;
if (myArray[i] < 0)
z++;
if(myArray[i]%2==0)
s++;
else
l++;
max = myArray[0];
min = myArray[0];
if(myArray[i] > max)
{
max = myArray[i];
}
if(myArray[i] < min)
{
min = myArray[i];
}
}
if ((myArray[i] >= -10000 && myArray[i] <= 10000)) //checks if arrays are in range
{
prumer=(float) sum/2;
pk = (float) k / c;
pz = (float) z / c;
ps = (float) s / c;
pl = (float) l / c;
printf ("\n");
printf ("Pocet cisel: %d\n", c);
printf ("Pocet kladnych: %d\n", k);
printf ("Pocet zapornych: %d\n", z);
printf ("Procento kladnych: %.2lf\n", pk);
printf ("Procento zapronych: %.2lf\n", pz);
printf("Pocet sudych: %d\n", s);
printf("Pocet lichych: %d\n", l);
printf ("Procento sudych: %.2lf\n", ps);
printf ("Procento lichych: %.2lf\n", pl);
printf("Prumer: %.2lf\n", prumer );
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
}
if (myArray[0]<-10000 || myArray[0]>10000) //checks if first element is in wrong range
programm prints arror and returns 0
{
printf("\n");
printf ("Error: Vstup je mimo interval!");
}
}
int
main ()
{
int lastArray = 0, end = 0, b = 0, i=0;
size_t arraySize = INITIAL_SIZE;
size_t numsEnteredSoFar = 0;
int *myArray = malloc (sizeof (*myArray) * arraySize);// initially make room for 10
if (myArray == NULL)
exit (-1);
while (1)
{
int curEntry, size = sizeof (myArray) / sizeof (int);
char ch;
if (scanf ("%d", &curEntry) == 1)
{
b = curEntry;
end = numsEnteredSoFar;
ch = fgetc (stdin);
myArray[numsEnteredSoFar++] = curEntry;
if (numsEnteredSoFar == arraySize)
{
arraySize += INITIAL_SIZE;
int *temp = realloc (myArray, arraySize * sizeof (*myArray));
if (temp == NULL)
{
fprintf (stderr, "out of memory\n");
exit (-1);
}
else
{
myArray = temp;
}
}
}
for (size_t i = 0; i < numsEnteredSoFar; i++)
if((myArray[i]<-10000 || myArray[i]>10000)) //checks if input is in range if not exits
{
if (i) //my attempt for making this work
printf (", ");
printf ("%i", myArray[i]);
printf ("\n");
printf ("Error: Vstup je mimo interval!");
exit (-1);
}
if (ch == 10)
{
break;
}
}
printArray (myArray, numsEnteredSoFar);
free (myArray);
return 0;
}
There are several ways to solve this problem:
Declare an array that's large enough to accommodate the largest conceivable size of your data.
Include a size at the beginning of your data, and use that to malloc your array.
Use a data structure that doesn't depend on a fixed size, such as a linked list.
This example allows the user to enter numbers "indefinitely" without the need for prompting how many to enter. Of course, your computer only has so much RAM, so there is a limit, but not a practical limit. Essentially, you need to choose an initial size, then allocate more space dynamically when that size is reached.
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10
void printArray(const int* myArray, size_t numsEntered)
{
for (size_t i=0; i<numsEntered; i++)
{
printf("myArray[%zu] = %d\n", i, myArray[i]);
}
}
int main(void)
{
size_t arraySize = INITIAL_SIZE;
size_t numsEnteredSoFar = 0;
int* myArray = malloc(sizeof(*myArray) * arraySize); // initially make room for 10
if (myArray == NULL) exit(-1); // whoops, malloc failed, handle this error how you want
while(1)
{
int curEntry;
printf("enter a number, or 'q' to quit: ");
if (scanf("%d", &curEntry) == 1)
{
// store in the array, increment number of entries
myArray[numsEnteredSoFar++] = curEntry;
// here you can check for positives and negatives, or
// wait to do that at the end. The point of this example
// is to show how to dynamically increase memory allocation
// during runtime.
if (numsEnteredSoFar == arraySize)
{
puts("Array limit reached, reallocing");
// we've reached our limit, need to allocate more memory to continue.
// The expansion strategy is up to you, I'll just continue to add
// INITIAL_SIZE
arraySize += INITIAL_SIZE;
int* temp = realloc(myArray, arraySize * sizeof(*myArray));
if (temp == NULL)
{
// uh oh, out of memory, handle this error as you want. I'll just
// print an error and bomb out
fprintf(stderr, "out of memory\n");
exit(-1);
}
else
{
// realloc succeeded, we can now safely assign temp to our main array
myArray = temp;
}
}
}
else
{
// the user entered 'q' (or anything else that didn't match an int), we're done
break;
}
}
// print the array just to show it worked. Instead, here you can
// loop through and do your comparisons for positive and negative,
// or you can continue to track that after each entry as you've
// shown in your code
printArray(myArray, numsEnteredSoFar);
free(myArray);
return 0;
}
Demo
Several parts to the answer.
Either declare a nice, big array, bigger than you'll ever need, or, prompt the user for the size, and then use that user-entered size to declare or allocate the array. (This is a popular strategy, but it's a lousy user experience, since the user shouldn't need to know or say how many numbers they're going to enter.)
Check the return value of scanf. If the return value isn't 1, this means that scanf failed, and didn't input a number. You can take this as an indication that the user stopped entering numbers.
Have two variables: the size of the array, and the number of numbers actually entered. You set the number of numbers actually entered by noticing when scanf failed. Then, later, when you work with the date in the array, you don't do for(i = 0; i < N; i++), you do for(i = 0; i < number_of_numbers; i++).
If you don't want to ask the user to explicitly enter the number of numbers, and you don't want to pick a "big enough" size in advance (either because you don't want to waste memory, or because you want to make sure the user can enter a lot of inout, potentially more than any number you picked), it's possible to dynamically reallocate an array bigger and bigger as the user enters more and more data, but that's an advanced topic.
Okay what am I doing wrong here?
This program is supposed to read 20 integers and then output an array of the integers that are not duplicates (Output each integer only once).
//Program to read 20 integers and return each integer only once (no duplicates).
#include <stdio.h>
int main()
{
int a, b, count=0, temp, array1[20];
printf("Enter 20 array elements between 1 and 10 inclusive\n");
for (a=0; a<20; a++) //Loop to enter 20 elements
{
scanf("%d", &temp);
for (b=0; b<=20; b++) //Loop to test each new element against all previous entered elements
{
if (array1[b] == temp) //If duplicate increment count
{
count++;
}
else if (count == 0 && b == 20) //If there have been no duplicates and 20 numbers have been tested... add entered number to the array
{
array1[a] = temp;
}
}
}
for (a=0; a<20; a++)
{
printf("%d\t", array1[a]);
}
return 0;
}
There are the following things wrong here.
In the inner loop, during the first check, you are comparing against 20 elements. On receiving the first element you do not have any elements to compare against. I have added a variable size to indicate the size of the array. size is initialized to 0.
The if (count == 0 && b == 20) should be moved outside the for loop and can be simplified to if (count == 0)
When an element is added to the array it is added at array1[size] and size is incremented.
You need to reinitialize count at every outer for loop as shown below.
The printing will print size elements that are non duplicate.
Code is below.
//Program to read 20 integers and return each integer only once (no duplicates).
#include <stdio.h>
int main()
{
int a, b, count=0, temp, array1[20];
int size = 0;
printf("Enter 20 array elements between 1 and 10 inclusive\n");
for (a=0; a<20; a++) //Loop to enter 20 elements
{
scanf("%d", &temp);
count = 0;
for (b=0; b<size; b++) //Loop to test each new element against all previous entered elements
{
if (array1[b] == temp) //If duplicate increment count
{
count++;
}
}
if (count == 0) //If there have been no duplicates and 20 numbers have been tested... add entered number to the array
{
array1[size] = temp;
size++;
}
}
for (a=0; a<size; a++)
{
printf("%d ", array1[a]);
}
return 0;
}
This code will accept 20 elements and store and display as many as were non duplicate (which can be 1-20). If you want to store 20 non duplicate elements (entering possibly many more than 20) it can be easily modified.
You have multiple reads of uninitialized variables which is undefined behavior. You also access the array out of range.
for (b=0; b<=20; b++)
^^
This will result in b in the range [0..20]
{
if (array1[b] == temp) //If duplicate increment count
^^^^^^^^^
array1[b] is uninitialized
and when b is 20 you access out of range
Further you only write to the array when count is 0 and b is 20
else if (count == 0 && b == 20)
{
array1[a] = temp;
}
Notice that you never reset count so after the first match you'll never write the array again
BTW - you print:
Enter 20 array elements between 1 and 10 inclusive
but you never perform any check of the input value to be in that range.
I want to make a program that applies some logic gates (AND, OR, XOR) to elements of two arrays of 1 and 0. But I am having problems with the user input of these arrays. I don't know how to make the arrays store only 1 and 0, for example if I type 5 I want the program to tell me it's neither 0 nor 1 and start over, I tried something but it's not working:
int v1[50],v2[50],i,j,n;
printf("Number of elements in arrays : ");
scanf("%d",&n);
printf("Introduce elements of first array :\n");
for(i=0;i<n;i++)
if(v1[i] == 0 || v1[i]==1)
scanf("%d",&v1[i]);
else (i'll make it a function and I want it to repeat if the elements given are not 1 and 0)
for(i=0;i<n;i++)
printf("%d",v1[i]);
In your first for loop, where you are reading the input, you should read the input first, and then decide whether you want to have the user try the input again. So, the first few lines of your for loop should look like this:
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
//Ask for another input, but do not advance i
}
}
This code will tell the user if they inputted a bad character, but it will not update the array correctly. To do this, all you need to do is decrement i once. This will make the previous "bad" value in v1 get overwritten.
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
We are not done, however. In your original code, you defined v1 to be an array of 50 elements. What if someone wants to input 51 elements? You would eventually end up with accessing an array index that is out of bounds, which could lead to some very big issues. So, you need to do some dynamic memory allocation using malloc
int *v1, i, n;
printf("How many elements will be in the bit array? ");
scanf("%d", &n);
//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));
You can read more about malloc here.
So, the whole code would look like this:
#include <stdlib.h>
#include <stdio.h>
int main() {
int *v1, i, n;
printf("How many elements will be in the bit array? ");
scanf("%d", &n);
//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));
printf("Input the elements of the first array (separated by newlines):\n");
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
Suppose you have an array consisting of 50 elements:
int v1[50];
If you want to fill it with values only of 0 and 1 you should set up a while loop, until the user puts in correct data:
int iter, result;
for (iter = 0; iter < 50; iter++)
{
while ((result = scanf("%d", &v1[iter])) != 1 // no number was found
|| (v1[iter] != 0 && v1[iter] != 1)) // OR it was and it wasn't 0 or 1
{
if (result != 1)
scanf("%*s"); // case 1: dispose of bad input
else
printf("Please, use only values 0 or 1\n"); // case 2: remind the user
}
}
}
I'm trying to create a program that will take inputs into an array, and then print them all when input is terminated. My understanding was that when you declare a variable outside of the loop, it keeps the values, but I can't get this to work out. I know there's a way to do this somehow, but I'm drawing a blank.
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=0;
int numbers[i];
scanf("%d", &numbers[i]);
while ((i = 1 && numbers[i-1] != 42)){
scanf("%d", &numbers[i]);
i++;
size++;
//printf("%d",numbers[i]);
}
printf ("%d", sizeof(numbers));
while ((n = 0 && n < sizeof(numbers))){
printf("%d", numbers[i]);
printf("\n");
++i;
++n;
}
}
Your while condition:
(i = 1 && numbers[i-1] != 42)
has two problems:
i = ... actually assigns a value to i. In cas of unexpected looping, allways check if there's a =instead of an == in the condition
due to operator precedence, you assign 1 && to i. That's true value (i.e. 1) as long as you're in the loop, and as soon as numbers[i-1] is 42, i turns to 0 (because numbers[i-1]!=42 is false and 1 && false is false i.e. 0 ). This gives you impression that it didn't keep the value.
Edit: Of course, it's the same principle for n in the second loop ;-)
3 things in your code:
int numbers[i]; is trying to declare a zero element array, which accounts to undefined behavior.(although there's no bound/range checking in C)
scanf("%d", &numbers[i]), when i>=1 where is the storage allocated for this? mostly would end up in an undefined area/ over writing an existing value.
Refer the following links for more information:
Declaring an array with 0 number of elements can still store values
Why does C not define minimum size for an array?
that said you could either declare an array of fixed size or declare the size dynamically using malloc, then loop through the elements , assign and print them.
-the while loop: evaluation and priority of operators:
you could re-write your program as:
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=0;
int numbers[42];
scanf("%d", &numbers[i++]);
while (((numbers[i-1] != 42)))
scanf("%d", &numbers[i++]);
size=sizeof(numbers)/sizeof(int); /* Not necessary as array size pre-defined*/
printf("\nsize:%d\n",size);
while(n < size)
printf("%d\n", numbers[n++]);
printf("\n");
}
Note: you can change the size of the array, do keep in mind that it's an automatic variable and those array elements which haven't been explicitly initialized would be filled with junk values.
There are a lots of mistakes in your code.They are as follow-
1.int i=0;
int number[i]; which makes no sense. because you are creating an array of size 0
while ((i = 1 && numbers[i-1] != 42))
every time you while loop iterates it sets the value of i to 1 and compares numbers[0]!=42 which also makes no sense.
while ((n = 0 && n < sizeof(numbers)))
again you are assigning n to 0 and checking if n is less than sizeof(numbers) which is always true.
Although you did not specify your problem correctly I am assuming that you want to scan number till you get 42. And after that you want to print the size of the array and the numbers too.
Here is your working code.
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=1;
int numbers[10000];//I am assuming maximum input to be 10000
scanf("%d", &numbers[0]);
i=1;
while (( numbers[i-1] != 42)){
scanf("%d", &numbers[i]);
i++;
size++;
//printf("%d",numbers[i]);
}
printf ("size=%d\n", size);
while ( n < size){
printf("%d", numbers[n]);
printf("\n");
//++i;
++n;
}
}
I'm trying to calculate HCF in C with pointers.
int-type-Pointer ptr points to an array of integers.
The inputs that i have given are 30,60,18,a. And here "a" is to terminate the list of integers and breaks off the "while".
I tried the debug mode, and found the values:
*ptr = 30
*(ptr+1)= -1163005939 //the garbage that i'm talking of.
*(ptr+2)= 60
*(ptr+3)= 30
while what i should get are 30, 60,18.
#include<stdio.h>
void main(){
int* ptr=(int*) malloc( sizeof(int)* 50);
int input=0;
int smallest;
printf ("Enter the numbers (press any alphabet when you're done )\n");
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
if (smallest > *(ptr+input)) // swapping
{ smallest += *(ptr+input);
*(ptr+input) = smallest- *(ptr+input);
smallest= smallest- *(ptr+input);
}
}
// code for determining the HCF
char c;
if (smallest <=0)
{
printf("", scanf("%c",&c ), printf("Answer is 0")); // it will print that the answer
exit(0); //is 0 then waits for you to
} //press any key and then it exits
//if smallest greater than 0
int i=2;
int HCF=1;
int j;
for (; i<smallest/2; i++)
{ for (j=0; j<=input;j++)
// this is where the problem is suspected
//as i ve seen in the debug mode
//it gives results divides the garbage value to i
{if (! (*(ptr+j)%i == 0)) // if the number stored in the location is not
break; //divisible by i, then leave that number i
} //and check for the next i
if (j>input)
HCF *= i;
}
printf( "", scanf("%c", c), printf("The HCF is %d ", HCF));
free(ptr);
}
So what is the problem?
And i didnt want to allocate the 50 ints memory. I wanted to just use the pointer wildly without any allocation. I know its bad practice but i just want to apply it . Is that any harm to other programs? How?
It's garbage because you never write anything to it. Look at this code
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
//code that doesn't assign values to ptr
}
by the time you get to scanf("%d",ptr+input ), input will be 2 if scanf("%d", ptr) returned a truthy value. That's because of this if statement:
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
notice how you continue here when input is equal to 1? that means that the while loop will skip everything else and begin again from the beginning, and the first thing that it's going to do is increment input from 1 to 2.