Finding max element in array - program won't recognize last element - arrays

I wrote this little code just to start learning some if statements and C coding in general. However, there is an issue. When running it, if the largest element is the last one, the code won't recognize it. Why is that?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int num[100];
int max;
int i;
printf("Enter 10 numbers: \n");
for(i = 1; i < 10; i++){
scanf("%d\n", &num[i]);
}
max = num[0];
for(i = 0; i < 10; i++){
if(max < num[i]){
max = num[i];
}
}
printf("The biggest nr is: %d", max);
return 0;
}

Your first loop should start from 0, not 1.
for(i = 0; i < 10; i++){
scanf("%d\n", &num[i]);
}
max already starts with an uninitialized value, here be dragons.

Inside of:
for (i = 1; i < 10; i++) {
scanf("%d\n", &num[i]);
}
max = num[0];
max has an indeterminate value because the loop's counter variable i starts at 0, not 1 which gives the result that the first element of the array wasn't assigned inside of the loop. So you end up assigning this indeterminate value to max.
To use an indeterminate value in the following code:
if (max < num[i]) {
max = num[i];
}
invokes undefined behavior.
"However, if I change i=0, the program asks me for 11 inputs before moving on. And among those 11 inputs, the program still won't count the last one, if it is the largest."
"When running it, if the largest element is the last one, the code won't recognize it. Why is that?"
It doesn't actually ask you for an 11th input for any presumed 11th array element as you think it does and the last in the loops1 treated element of the array is not the one you think it is. That is just an impression to you.
This behavior is caused by the newline character in the format string of the scanf() call:
scanf("%d\n", &num[i]);
The newline character (\n ) is equal to any white space and with this directive, scanf() reads an unlimited amount of white space characters until it finds any-non white space character in the input to stop consuming and the control flow continues to the next statement.
Why does scanf ask twice for input when there's a newline at the end of the format string?
It doesn't ask for the input of the 11th element of the array (as you think it does). It simply needs any non-white space character that the directive fails.
The last element of the array (which is treated inside of the loops1) is still the 10th (num[9]), not the 11th (num[10]) and so is the output correct when you initialize the counter to 0 and it prints:
The biggest nr is: 10
because 10 is the value of the last treated element num[9].
1) Note that you made a typo at the declaration of num -> int num[100];. With this you define an array of one hundred elements, but you actually only need one of 10 elements -> int num[10];.
Side Note:
Also always check the return value of scanf()!
if (scanf("%d\n", &num[i]) != 1)
{
// Error routine.
}

There are two problems in the code one after another:
The loop should begin from 0 instead of 1:
for (int i = 0; i < 10; i++)
The main problem is here:
scanf("%d\n", &num[i]);
_________^^____________
Remove the \n and your problem will be fixed.

Related

Enter unknown number of array values in C/C++ has strange behaviour

I need to populate an array of integers with an unknown number of elements. I am using a while loop to input values and exit the loop as a non integer value is entered. Outside the loop an integer j is initialized at 0 and used to address array elements inside the loop. At each round of the loop I check the value of j before and after the input value is assigned to array element v[j], then j is incremented.
Depending on the size chosen for the array in the declaration, (in the example below v[8]), index j is unexpectedly affected by the assignment itself: in the example below when j equals 11 before the assignment it becomes 2 after the assignment, thereafter messing it all up. As a result the code fails to assign the correct input values to the array.
I am surely lacking some deeper knowledge about C/C++ array management... anyone can help to to fill the gap explaining the apparently strange behaviour of my code?
#include <stdio.h>
int main()
{
int j = 0, m, v[8];
printf("Enter an integer: to finish enter x\n");
while (scanf("%d", &m))
{
printf("j before assignment:%d - ", j);
v[j] = m;
printf("j after assignment:%d - ", j);
printf("v[j] after assignment:%d\n", v[j]);
j++;
}
return 0;
}
You write beyond the array boundaries of v. To avoid this, check j in a for loop, e.g. replace while (...) with
for (j = 0; j < 8 && scanf("%d", &m) == 1; ++j) {
// ...
}
This way, the loop stops after the end of the array (v[7]) is reached.
To comment the "strange" behaviour, read about stack and stack layout, e.g. Does stack grow upward or downward?
As always, check the C tag wiki and the books list The Definitive C Book Guide and List

Error: Stack around the variable "m" is corrupted

Im trying to make a program which says how many times a specific digit appears on a 100 numbers sequence.
Meanwhile I got this error and I can´t understand what is the solution to this. I´d appreciate if you could get me some tip or the solution.
#include <stdio.h>
int main() {
int i, m, digit, val[99], count=0;
printf("Enter a number:");
scanf("%d", &val[0]);
while (val[0] < 0) {
printf("Enter a number:");
scanf("%d", &val[0]);
}
for (i=1;i<101;i++) {
val[i]=val[0]++;
printf("%d\n", val[i]);
}
printf("Enter a digit:");
scanf("%d", &m);
while (m<0||m>9) {
printf("Enter a digit:");
scanf("%d", &m);
}
do {
digit=val[i]%10;
val[i]=val[i]/10;
if (digit==m) {
count++;
}
}while (val[i]>0);
printf("The digit %d is printed %d times in this sequence.", m, count);
}
In the for loop you step outside of the array val of which the last index is 98. Instead of hard-coding the length of the array in several places it is more convenient to use a length macro, like this:
#define LEN(anArray) (sizeof (anArray) / sizeof (anArray)[0])
...
for (i = 1; i < LEN(val); i++) {
...
Also, in the do-while loop the index i is outside of the array bounds of val. You also need to check the return value of scanf to make sure the input is valid. The last printf statement also needs a trailing newline.
Edit: Note that LEN only handles "real" arrays; arrays passed to functions are received as pointers.
You allocated only int /* ... */ val[99] (only val[0] to val[98] are available) and accessed upto val[100] because the loop condition is i<101.
This will lead to dangerous out-of-range write (undefined behaior).
Allocate enough elements like int /* ... */ val[101] or fix the loop condition not to cause out-of-range access.
Also you didn't set value of i after the for (i=1;i<101;i++) loop, so value of uninitialized element will be used in the do ... while loop. Values of uninitialized elements of non-static local variables are indeterminate and using the value invokes undefned behavior.
Set i to proper value before the loop or change the indice i to proper thing.

How to delete an additional character on the pyramid (CS50 Mario Program) formed by this code to be right aligned?

I'm currently taking CS50 course. At the very first assignment, I need to create a pyramid in C, using hashes (#) which allows the user to decide just how tall the pyramid should be by first prompting them for a positive integer between, say, 1 and 8. The expected output and the output that I receive as follows; [https://i.stack.imgur.com/0Qkg5.png]. I somehow managed to add one space on each row, does anyone have any idea to how to fix that?
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
do
{
n = get_int("Enter the height: ");
}
while (n<1 || n>8);
for (int i = 1; i<=n; i++ )
{
for(int spaces = (n-i); spaces>=0 ;spaces--)
{
printf(" ");
}
for(int dashes = 1; dashes<=i ; dashes++)
{
printf("#");
}
printf("\n");
}
}
Consider the case where n == i, which happens in the last row of the pyramid. The way you've written your for-loop, it will still run once, because spaces gets set to zero. But on the last row, you need no spaces, the for loop shouldn't even run once. The fix is simple: Change spaces >= 0 to spaces > 0. That way the loop only runs exactly spaces times (which might be zero), and not spaces+1 times like it is now.

Find the missing number from 1..N

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", ...);

How to add the first number and last number of a series of number in C?

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;
}

Resources