This question already has answers here:
Why am I getting a strange number in this code?
(5 answers)
Closed 2 years ago.
I have a simple program that is supposed to ask the user for 10 integers and print them out, but instead of printing the integer it prints a random 7 digit number that increases by 4 for every new int.
#include <stdio.h>
int main(int argc, char *argv[])
{
int number = 0;
int numbers[10];
for (int i = 0; i < 10; i++)
{
printf("Please enter 10 numbers: ");
scanf_s("%d", &number);
numbers[i] = &number;
printf("Your number was %d\n", &numbers[i]);
}
}
And the program ends up doing something like:
Please enter 10 numbers: 1
Your number was 5241560
Please enter 10 numbers: 2
Your number was 5241564
Please enter 10 numbers: 3
Your number was 5241568
And so on, with a different 7 digit number every time, but always increasing by 4.
The numbers that you might think of as random in this case are not random after all! They're actually addresses of the array elements. Why?
Well because in your printf you print out &numbers[i]. Putting the '&' sign means accessing the address of certain value, as opposed to accessing the value itself.
Therefore if you're interested in printing array elements as opposed to addresses of array elements then you should remove '&' form your printf statement.
Also numbers[i] = &number; means "assign address of variable number to ith element of array. You should remove unnecessary '&' signs if accessing addresses is not what you actually want.
Here are some good references on addresses in C:
Pointers in C,
5 Minute guide to C pointers
You use & unnecessarily. Replace
numbers[i] = &number;
with
numbers[i] = number;
and
printf("Your number was %d\n", &numbers[i]);
with
printf("Your number was %d\n", numbers[i]);
You also don't use int argc, char *argv[] parameters so replace
int main(int argc, char *argv[])
with
int main(void)
Related
In an interview they asked me to find out the missing number from an array.
array will be having number from 1 to N.
My Approach:
int main()
{
int ar[20];
int sum = 0;
int n;
printf("enter numb of elements\n");
scanf("%d", &n);
printf("enter array numbers\n");
for(int i = 0; i<n;i++){
scanf("%d", &ar[i]);
sum +=ar[i];
}
printf("missing num=%d", ((n*(n+1))/2)-sum);
}
But interviewer did not call back after first round of interview.
I don't know what is wrong with my approach.
Some issues with your code:
The algorithm is wrong (off by one): If the array contains all numbers from 1 to N except for one missing number, then it has N-1 elements. Your code reads N elements. (Alternatively, if the array actually has N elements, then the target sum is (N + 1) * (N + 2) / 2 (sum of numbers from 1 to N+1), not N * (N + 1) / 2.)
Includes are missing (in particular, #include <stdio.h>). That means the calls to printf / scanf have undefined behavior.
int main() should be int main(void).
None of the scanf calls check their return value. That means your code doesn't realize when reading input fails, producing garbage output.
If n is bigger than 20, your code silently writes outside the bounds of ar. That's a classic buffer overflow.
The previous point is especially unfortunate because your code doesn't even need the array. All you do with the input numbers is to add them up in sum, which doesn't require a separate array.
Your formatting is inconsistent in for(int i = 0; i<n;i++){. Why is there no space in for(int and i<n;i++){, but there are spaces around i = 0;?
Depending on how big N is, n*(n+1) could overflow.
The last line of output produced by your code is missing its terminating newline: printf("missing num=%d\n", ...);
I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}
I have this simple problem to which I am trying to write a solution, in C.
If an array arr contains n elements, then write a program to check
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.
And my code looks like this-
#include<stdio.h>
int main()
{
int arr[10],i=0,j;
int k=0;
printf("\n Enter 10 positive integers: \n");
for(k=0;k<=9;k++)
scanf("%d",&arr[k]);
while(i<=9)
{
for(j=9;j>=0;j--)
{
if(arr[i]==arr[j])
{
printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
}
i++;
continue;
}
}
return 0;
}
On entering this input-
Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90
The output I get is-
The array element 20 is equal to array element 20
The array element 40 is equal to array element 40
The array element 40 is equal to array element 40
The array element 20 is equal to array element 20
Now, there are two problems with this code-
As you can see, the program prints out matching array elements twice. This is because, the way I've structured the program, once the variable i loops through the array from the first to last element, and then j loops through from the last to first element. So each prints out the matching array element once, leading to two sets of values.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
I've read that, in C, array dimensions(when declaring) cannot be a variable. So, a declaration like this(which was my first thought) wouldn't work-
int n; // n is no. of elements entered by the user
int arr[n];
I'm a newbie to programming, so my apologies if the question sounds/is too simple, low-quality.
Thank You.
1)You can traverse the array for half times for getting the prints only once. Instead of for(j=9;j>=0;j--) you can use for(j=9;j>=9/2;j--).
2)
int n;
int arr[n].
Recent Compilers support this statement. If you don't like to use this, you can go for dynamic memory allocation for the array.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
Use dynamic memory allocation. Use malloc().
So code will be
{
int num_elements;
int* arr;
printf("Enter number of elements\n");
scanf("%d", &num_elements);
arr = (int *) malloc(num_elements * sizeof(int)); // Use this 'arr' for holding input data from user
// Your remaining code comes here
free(arr); // Free the pointer in the end of program
}
the variable length creation works for me:
#include<stdio.h>
int main(){
int a, i;
scanf("%i", &a);
int blah[a];
for (i = 0; i < a; i++){
printf("/n%i", blah[a]);
}
}
The other way would be to create the maximum length array and than simply use first n elements.
As the previous answer states it is up to you to make sure you are checking each element only once therefore stopping at the element n/2. It is probably important that n/2 is rounded to the closest smaller integer, so at first glance odd numbers of arguments may be differently handled. But as it is omitting only the middle element it is identical to itself.
For your first query
for(i=0;i<n/2;i++)
{
if(a[i]==a[n-(i+1)])
{
printf("\n The array element %d is equal to array element %d\n",a[i],a[n-(i+1)]);
}
}
For your second query you can use condition i<(n/2) (which runs the loop (n/2)-1 times) For your case where n = 10 it will run from 0 to 4.
If you want to loop from 0 to 9 you can use
for(i=0;i<n;i++)
For making array of n elements where n is a variable either make an array of elements that is always greater than n or do it by making a dynamic array.
http://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
corrected:
#include<stdio.h>
int main()
{
int i=0, size; // size of array
int k=0; // counter
printf("enter size of array\n");
scanf("%d", &size); // ask user for desired size
int *arr = malloc(size * sizeof(int)); // allocate memory for array
printf("\n Enter 10 positive integers: \n"); // fill your array of size size
for(k=0;k<size;k++)
scanf("%d",&arr[k]);
k = 0; // reset this counter
for(i=0; i<size/2; i++) // check only for half of it
{
if(arr[i] == arr[size-i-1]) // try it with paper and pincil
{
printf("match arr[%d]=arr[%d]=%d\n", i,size-i-1, arr[i]);
k++;
}
}
if(k==0) printf("No matching");
return 0;
}
I need to make a program where the user types numbers( such as 193643, in one line).
Then have each number (such as"1" "9" "3" etc) turned in to its own variable.
how do i do it?
I haven't attempted as i dont get it, I will try my best to explain.
similar to...
printf("Please enter three numbers: ");
scanf("%d",&number1);
The user types 137
Instead of entering 137 and having that become the variable. I need to make it so that If the person enters a number like 137, The program takes "1" as a variable, "3" as another variable and "7" as the last variable. It must be in one line...
SO instead of asking three times as so....
printf("Please enter 1st numbers: ");
scanf("%d",&number1);
printf("Please enter 2nd numbers: ");
scanf("%d",&number2);
printf("Please enter 3rd numbers: ");
scanf("%d",&number3);
have it ask in one line, one time and record each number as a variable...
If I understand your question, you are trying to extract every number and store it into a variable. A small example is as below
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char inpString[20];
int num;
strcpy(inpString, argv[1]);
num = atoi(inpString);
printf("Number: %d\n", num);
while(num > 0)
{
printf("%d\n", (num % 10));
num = num / 10;
}
printf("Size of void *: %d\n", sizeof(void *));
return 0;
}
I figured it out thanks everyone! it just required some simple problem solving, I will share just in case some one else is trying to figure it out as well....
Note: separate is just a variable i created to separate each number one by one. I made all the variables integers.
separate = 137 for this example.
lastDigit = separate % 10;
separate = separate / 10;
secondDigit = separate % 10;
separate = separate / 10;
firstDigit = separate % 10;
7 is stored in lastDigit. Then 7 is shaved off from separate variable (137 to 13).
3 is stored in secondDigit. Then 3 is shaved off from separate variable (13 to 1).
1 is stored in firstDigit.
I wrote the following code for
this
Given an integer number, Write a C program that displays the number as follows:
First line : all digits
Second line : all digits except first digit
Third line: all except first two digits
last line : the last digit
For eg.,
the number 5678 will be displayed as:
5 6 7 8
6 7 8
7 8
8
=>
#include<stdio.h>
#include<math.h>
main()
{
long int x,y,n,z,i=1;
printf("enter no. of digits=");
scanf("%d",&n);
printf("x=");
scanf("%d",&x);
while(i<=n)
{
y=x/pow(10,i);
z=y*pow(10,i);
printf("%d\n",(x-z));
i++;
}
}
The code works(if we ignore the formatting) but does some rounding of and stuff fr some output values ...don't know why??
There are solutions using array and all...but whts wrong with this one??
I'm assuming by "some values" with problems, you're referring to values that have zeroes in them, such as input like 50345, which will print:
50345
345
345
45
5
rather than:
50345
0345
345
45
5
The problem is that the integer representation of numerical values does not acknowledge leading zeroes as being a unique integer value.
If you must print the values, including leading zeroes, you're going to have to treat your number like a token or string, meaning that a value that has leading zeroes is a unique string value from the version without leading zeroes. This is why the array-versions, which treat the numeral value like a string, work, and your current version does not when presented with this type of input case.
The rounding off you are seeing could be because of the use of int as data type for all the variables. So something like (5/10) would be rounded to 0 and not 0.5.
#include<stdio.h>
#include<math.h>
main()
{
int num, count=0, x,no;
printf("Enter a number\n");
scanf("%d",&num);
no=num;
printf("The number you entered is:\n %d\n",num);
while(num){
num=num/10;
count++;
}
for(;count>1;count--){
x=pow(10,count-1);
printf("%d\n",no%x);
}
}
#include <stdio.h>
#include<conio.h>
void main()
{
int number,i=0;
int digits[8];
scanf("%d"&number);
while(number!=0)
{
digits[i]=numder%10;
number=number/10;
i++
}
for(i=i-1;i>=0;i--){
for(j=i;j>=0;j--){
printf("%d ",digits[j]);
}
printf("\n"):
}
}