I have an assignment and I was wondering why when I compile this code and run it, the scanf("%d", &temp_pin) doesn't store the data in an address. I know this because in the next statement of printf("%d", temp_pin) I'm just given random variables. I have another scanf statement in the earlier lines of code that work and I`m just stumped as to why this one doesn't. Many thanks!
#include <stdio.h>
int main()
{
//Deceleration of Variables
int option;
int pin [4]={1, 2, 3, 4};
int temp_pin [4];
int new_pin [4];
int temp_new_pin [4];
int correct;
int incorrect;
do
{
printf("Please enter which option you wish to operate\n\n");
printf("1. Enter your pin\n");
printf("2. Change your pin\n");
printf("3. Display the number of times the PIN was entered: \n Successfully\n Unsuccessfully\n");
printf("4. Exit Program\n\n");
scanf("%d", &option);
if (option == 1)
{
printf("\nPlease Enter Your PIN\n");
for (int i = 0; i < 4; i++)
{
scanf(" %d", &temp_pin);
printf(" %d", temp_pin);
if (temp_pin==pin)
{
printf("\nYour PIN is correct\n");
}
if (temp_pin != pin)
{
printf("\nYour PIN is incorrect\n");
}
}//End For
}//End If
} // end do
while(option != 4);
return 0;
}
If I could make one suggestion it would be changing all the integer arrays into integers. This would fix all of your problems. However, if your assignment requires the use of integer arrays please follow the code below.
Currently you are setting only the first element of temp_pin equal to the user input. The line scanf(" %d", &temp_pin); actually stores an integer into temp_pin[0].
Since the pin size is 4, you would need to read in 4 separate integers to store in the array. I would suggest using a for loop that can set the values of temp_pin[0], temp_pin[1], temp_pin[2], temp_pin[3]
Logically, I would also suggest error checking each integer, since an integer can be from size -32,768 to 32,767. Currently an integer array with the elements 3300,55,12,15 would be a valid pin.
The value you are given in this line printf(" %d", temp_pin); is not random variables. This is the address of temp pin. In order to print the values stored in temp_pin you would need to iterate through each element in the array and print it individually.
For your compare statement if (temp_pin==pin), this would never result in true since it is comparing addresses. Again the proper fix for this would be to iterate through both lists simultaneously and compare each element.
You have temp_pin declared as an array of integers, so &temp_pin is a pointer to an array and has type int (*)[4]. The %d format specifier expects an int *.
Similarly, when printing you pass the array temp_pin which decays to a pointer to the first element, and that address is what is being printed.
Change the type of temp_pin and the other variables declared as arrays to int and remove the loop.
int pin = 1234;
int temp_pin;
int new_pin;
int temp_new_pin;
...
if (option == 1)
{
printf("\nPlease Enter Your PIN\n");
scanf(" %d", &temp_pin);
printf(" %d", temp_pin);
if (temp_pin==pin)
{
printf("\nYour PIN is correct\n");
}
else
{
printf("\nYour PIN is incorrect\n");
}
}//End If
You attempt to read an array with one scanf call, but it does work like that in c. Note that temp_pin is already an address of the first element in the array.
The line
scanf("%d", temp_pin);
is equivalent to the line
scanf("%d", &(temp_pin[0]));
and it reads the value and stores it at temp_pin[0].
In order to read the whole array you'll need to do something like this:
for (int i=0; i<4; i++) scanf("%d", &(temp_pin[i]));
The same story with the comparison. You can't compare two arrays with one == operation. The expression temp_pin == pin compares the addresses which will always be different despite the actual values that are stored in those arrays. In order to compare two arrays you'll need to do something like this:
int isEqual = 1; // a flag for whether arrays are equal
for (int i=0; i<4; i++) {
if (temp_pin[i] != pin[i]) {
isEqual = 0;
}
}
if (isEqual) printf("pins are the same\n");
else printf("pins are not the same\n");
Related
This is my code
#include<stdio.h>
int main()
{
int n,a[n],op;
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[n]);
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}
Output
Enter size of the array
5
Enter the array elements
2
5
6
1
5
Select array element to display from 1 to 5
2
Element is 0
Why is this happening? I couldn't figure this out
Consider your code:
int n,a[n],op;
Given that the value of n is undefined at this point, the variable length array (VLA) created by a[n] will be of some arbitrary size. C doesn't magically reach back in time from the point where you request a value of n and adjust the array size :-)
You need to create the VLA after you've set the value of n, reorganising your code at the start of main with something like this:
int n,op;
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n];
That way, n will be a known value when you use it to create the VLA.
Additionally, your scanf("%d",&a[n]); is undefined behaviour because n will always be beyond the end of the array (which has indexes 0 through n-1 inclusive). You should be using i as the index there.
There are other logic issues such as checking that the scanf succeeded and that you didn't enter a non-positive number but that's usually okay for educational code (assuming that's what this is). As you develop as a coder, you will naturally begin to think of these possibilities and harden your code accordingly.
By way of example, this is a better way to enter n, although you could recover from non-numeric data as an optional extra (see here for a nifty line input solution in C):
int n = -1;
while (n < 1) {
printf("Enter array size (positive integer): ");
if (scanf("%d", &n) != 1) {
puts("\nERROR: non-numeric");
exit(1);
}
}
scanf("%d",&a[n]);
should be scanf("%d",&a[i]);
The error is in this part of your code:
int n,a[n],op;
// int n is not defined as anything so it is a garbage value
// you specify the size of the array to be n
// which allocates an undefined size for the array
Also in your first loop you reassign &a[n], which is undefined since it goes beyond the size of the array and even if it were valid it would just reassign a single element, it should be &a[i].
to fix it read the value of n before defining array 'a'. The changes i made are down below:
#include<stdio.h>
int main()
{
int n; // change
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n],op; // change
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]); // change
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}
How do i assign a value to a different variable every time the loop activates? I want to change the variable inside a scanf() so that when a new number is assigned to a different variable. Like in:
int a,b,c,i;
for(int i=1;i<=3;i++)
{
printf("enter a number:");
scanf("%d",&a);
}
The loop asks for numbers 3 times, and i want to enter 1,2, and 3. How can i assign them in a different variable each? Like 1 is assigned to a, b=2, and c=3?
You cannot change variable names at run-time, because simply they don't exist at runtime. If the type of inputs are of the same type, say, integer, you can use an array of integers to store multiple inputs.
Sample:
int array[3] = {0};
//input
for(int i=0;i<3;i++)
{
printf("enter a number:");
scanf("%d",&(array[i]));
}
//output
for(int i=0;i<3;i++)
{
printf("Number %d is %d", i+1, array[i]);
}
Thats what arrays were made for!
int numbers[3];
for(int i=0;i<3;i++)
{
printf("enter a number:");
scanf("%d",&numbers[i]);
}
Then your three numbers are available via:
numbers[0], numbers[1], numbers[2]
I'm writing a program that requires me to do a union of two arrays. Here is my code so far.
I get Segmentation fault as an error after I enter set A.
#include <stdio.h>
void Union(int a[], int b[], int set1, int set2)
{
int u[20], i, j, unionIndex=0,trigger;
for(i=0; i<set1; i++)
{
u[unionIndex] = a[i];
unionIndex++;
}
for(i=0; i<set2; i++)
{
trigger=0;
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
{
trigger =1;
break;
}
}
if(trigger =0)
{
u[unionIndex]=b[i];
unionIndex++;
}
}
for(i=0;i<unionIndex;unionIndex++)
{
printf(" %d",u[i]);
}
}
int main(void) {
int N=0;
int M=0;
int i;
int j;
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
int a[N];
printf("Enter the numbers in set: ");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Please enter the number of elements in set B: ");
scanf("%d",M );
int b[M];
printf("Enter the numbers in set: ");
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
Union(a,b,N,M);
return 0;
}
I'm pretty sure the issue has something to do with arrays because the program will compile but i get the error right after the user enters set A. I'm a beginner at C but I know a lot more about Java, so I'm thinking this has something to do with memory allocation. I'm not really sure how to solve the issue, so if you could point me in the right direction that would be helpful.
You need to pass the address of the variable to scanf()
Change
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
to
printf("Please enter the number of elements in set A: ");
scanf("%d", &N);
Same goes for other place
printf("Please enter the number of elements in set B: ");
scanf("%d", &M);
There is another possible mistake
Its here
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
In this set1 is equal to N, so j will go from 0 to N-1. And array u[] has only 20 elements. There is a possibility of array access out of bound if some user enter value more then 20 for N.
The problem, as I see it is in
scanf("%d",N );
and
scanf("%d",M );
It invokes undefined behavior as scanf() needs the argument to a format specifier to be a pointer to the type.
Just to clarify, you're essentially passing the address as 0 (value of the variable), which is not a valid addres, anyway.
You need to pass the address there, like
scanf("%d", &N );
and
scanf("%d", &M );
That said, in your Union() function, you're using a user-defined value to limit the for loop, against a constant value 20. In case the user input is more than 20, you'll be overrunning the memory which invokes undefined behavior.
The reason you're getting the segmentation fault is because of how you're calling scanf when reading in N and M. The %d format specifier for scanf expects an int *, i.e. the address of an int, but you're passing in an int. This is undefined behavior.
So you can fix them like this:
scanf("%d",&N );
....
scanf("%d",&M );
Some addtional bugs:
When looping to read in the values for b:
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
You have the wrong loop indexes:
for(j=0;j<M;j++)
{
scanf("%d",&b[j]);
}
When checking trigger:
if(trigger =0)
This is an assignment, not a comparison:
if(trigger == 0)
When looping to print out u:
for(i=0;i<unionIndex;unionIndex++)
You're incrementing the wrong variable:
for(i=0;i<unionIndex;i++)
Finally, u need to have a length of at least set1 + set2, otherwise you risk writing off the end of the array:
int u[set1+set2];
Fix those and you should get the desired results.
I have to write a function which checks if a value is located in an array with N elements using for loop.I wrote the code
#include <stdio.h>
int main ()
int N[100],n,i;
printf ("Write the value of n:");
scanf ("%d",&n);
i=0;
printf ("Write the value of the element :");
scanf ("%d",&v[i]);
for (i=0,i<n,i++)
{
if (N[i]==n)
}
printf ("The value is located in the array :");
return 0;
When I compile it,it says syntax error before printf.What does this mean?What have I done wrong?
Basic syntax issues. Try:
#include <stdio.h>
int main(void)
{
int N[100],n,i;
printf ("Write the value of n:");
scanf ("%d",&n);
i=0;
printf("Write the value of the element :");
scanf("%d", &v[i]); /* v doesn't exist */
/* you are looping up to n, which could be anything */
for (i=0; i<n; i++)
{
/* you never populate N, so why would you expect n to be found?
the value of any element in N is indeterminate at this point */
if (N[i]==n)
{
printf ("The value is located in the array :");
}
}
return 0;
}
That said, you have logical problems here:
v is not declared anywhere.
You never populate your array (N).
n is a value entered by the user, not the upper bound of the array. What if I enter 101?
Those are more than syntax issues, you'll need to fix your logic.
Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). I.e. as a white space delimited list.
So far:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
Not sure how I might do this?
Thanks
scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). This means that a line like:
scanf("%d", &no);
actually reads and ignores all the whitespace before the integer you want to read. So you can easily read an arbitrary number of integers separated by whitespace using a for loop:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. Also you shouldn't have a semicolon after your #include statement. The compiler should give you a warning if not an error for that.
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
You can try it like this.