c-fill a one dimensional array with for loop - arrays

I can understand the first solution.But in the second solution i am confused about the way scanf, accept 4 values at the same time and apply them to the for loop.
//first solution
#include <stdio.h>
int main() {
int pin[4],i;
for(i=0; i<4; i++){
printf("Give value: ");
scanf("%d", &pin[i]);
}
return 0;
}
//second solution
#include <stdio.h>
int main() {
int pin[4],i;
printf("Give 4 values: ");
for(i=0; i<4; i++){
scanf("%d", &pin[i]);
}
return 0;
}

The difference is only that in the first example there is a printf that asks you for the input values at every iteration of the cycle while in the first example there is a printf (only one) before the cycle.
The operation that matters (the scanf) is exactly the same in the two examples.

The scanf commamd does not read four values at the same time.
This is an example of a loop: a piece of code that does the same thing multiple times.
for(i=0; i<4; i++){
scanf("%d", &pin[i]);
}
What the for statement does is, first initialize i to zero, then check that i is less than four, then, execute the code within its curly braces. That's the scanf statement, which attempts to read an integer to the address specified by &pin[i]. Since i is zero, that means, the address of pin[0], which is the first element of the array pin.
After the scanf executes (and whether or not it succeeds, which is something you may want to look into) the for statement increments the value of i, checks that it is still less than four, and executes the block of code between the braces again. This time, the scanf statement attempts to read to pin[1].
The loop executes two more times, potentially storing integers in pin[2] and pin[3] before terminating just after incrementing i to 4.

Related

Infinite for loop? ()in c

the value of i resets after it reachers 7
#include <stdio.h>
int main(){
char marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
output
Problem is here:
scanf("%d", &marks[i]);
Specifier "%d" expects a pointer to int, not char. Usually it will write 4 bytes what is a typical size of int.
Therefore on 8th iteration the elements of marks at index from 7 to 10 are touched. However, marks[10] is outside of marks array (only indices 0-9) are valid. Undefined Behaviour is invoked and the program can do anything, from crashing to infinite looping or conjuring nasal deamons.
To fix the program change the type of marks to int:
int marks[10];
Note:
UB is invoked even on the first iteration because "%d" expects a pointer to int while type of &marks[0] is char*. This operation is undefined by C standard because int* and char* may differ in size and/or representation and/or alignment. However it is a unlikely case for modern CPUs.
You have declared the marks as a character array and tried to get input from user using %d which asks asks for an integer,
#include <stdio.h>
int main(){
int marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
Also I didn't understand the use of all so I couldn't find a solution for it. If you want to print a specific number then you have to specify it like you have done it for second or if you want to display the total you want to add a furthermore code to calculate the sum of elements in the array.

How do I determine if a value is within a range?

I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.
Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%s", i);
if (i>4 && i<6){
printf("%s Value is in first interval\n", i);
}
}
The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.
It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%d",&i);
if (i>4 && i<6){
printf("%d Value is in first interval\n", i);
}
}
try compiling your code without if condition i variable will return a null value

Unable to convert values from lowercase to uppercase using toupper

i'm attempting to create a program that asks the user to firstly enter the amount of values they would like to convert from lowercase to uppercase. The for loop then assigns each value into an array. The array then goes through another for loop to convert the values into uppercase using LowerToUpper function.
When i go to run the program, it will take in values and then start doubling them on the command window, and will cease when you have completed entering the values, rather than printf the results. Could you please explain why. Thank you in advance
#include<stdio.h>
#include <string.h>
#include <ctype.h>
void LowerToUpper(char* array)
{
toupper(*array);
}
int main(void)
{
int i, amount;
printf("How many values?\n");
scanf("%d", &amount);
char *d;
char array1 [amount];
printf("Please enter the values\n");
for(i=0; i<amount; i++)
{
scanf("%c", &array1[i]);
}
for(i=0; i<amount; i++)
{
d=&array1[i];
LowerToUpper(d);
scanf("%c", &array1[i]);
printf("%c", array1[i]);
}
return 0;
}
You are not using toupper() properly. The function returns the converted value in case of success. You need to make use of the returned value. The supplied argument is not changed.
That said, the program structure is unnecessarily complicated. you can simplify it like
for(i=0; i<amount; i++)
{
int result = toupper (array1[i]);
if (result != array1[i]) printf("%c", result); //just checkin', if converted
}
That said, you have many other issue which you don't see at this moment, like
scanf("%c", &array1[i]);
this will, to your surprise, only ask you for half the number of inputs. Why? You forgot to ignore the newline entered by RETURN key.
Then, you did not check for the success of scanf("%d", &amount); call. In case, the scanning fails, you'll end up with undefined behavior.
The second scanf() inside the last for loop is probably something you don;t want, it's useless, at best.
Change this:
toupper(*array);
to this:
*array = toupper(*array);
since toupper ref's mentions:
Return Value
The uppercase equivalent to c (*array in your case), if such value exists, or c (unchanged) otherwise. The value is returned as an int value that
can be implicitly casted to char.
PS: Defining a function LowerToUpper() for this operation (one line of code) is an overkill, and you could call that one line of code inside main() instead (I mean the body of the function to be moved into main()).

While loop not repeating in c

I have to create a program that requests integer numbers from the user
repetitively though the keyboard until the user enters 0. I've gotten to the while loop and its not repeating and I'm not sure why. Any help would be greatly appreciated.
Thanks
Edit: I've fixed the loop in terms of it not repeating but now it's infinitely repeating and I have no clue why.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char first[30], last[30];
int n, even, odd, etotal = 0, ototal = 0;
printf("What is your first name?\n");
scanf("%s", &first);
printf("What is your last name?\n");
scanf("%s", &last);
// asks for name
printf("Enter a number\n");
printf("To quit the program enter 0\n");
scanf("%d", &n);
while (n!=0){
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++; }
}
return 0;
}
The loop isn't repeating because you have a return statement in the loop, that will leave the main function immediately. Just remove it.
You also have another problem that's much worse: Undefined behavior. Local non-static variables, like for example n in your code, don't get initialized, instead they have an indeterminate value. Attempting to use such an uninitialized variable leads to said undefined behavior.
You need to explicitly initialize the variable to some value before using it in the condition, for example to reorder the code so you read input before the loop and then also at the end of the loop.
Local variable n is uninitialized producing undefined results collaboratively called undefined behavior. Initialize it before entering loop:
n = 1;
And check result of scanf:
if (scanf("%d", &n) != 1)
// error
Because n is not initialized, so it has a random value:
int n, even, odd, etotal, ototal;
/* ... */
while (n!=0){
Loop is not working because you didn't initialize n and unnecessary return 0 inside the while loop. You can fix it with do..while as below. Because you have the input statement as your first statement, do..while is best opted here.
do{
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++;
}
else {
printf("%d is odd.\n",n);
ototal++;
}
} while (n!=0);
You use scanf to read your input, but after your if/else statement you are returning 0 hence you are leaving the program. So it doesnt matter if you write an even or an odd number.
while (n!=0){
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++;
}
return 0;
}

How to limit the input on a 2D array so it won't blow up?

I have a small program, where i say the number of lines and columns of a array I want to input, then input info to fill that array with data. What it does next it's not important so ill just omit that part of the code and put (...) in it.
int main (){
int nl, nc,i,j,z,n;
scanf ("%d %d\n", &nl,&nc);
char matrix [nl] [nc];
for (i=0;i<nl;i++)
for (j=0;j<nc;j++)
scanf(" %c",&matrix[i][j]);
scanf("%d",&n);
int s[n*2];
for (z=0;z<n*2;z++)
scanf("%d",&s[z]);
int y=0;
char s2[n];
for (z=0;z<n*2;z+=2){
s2[y]=matrix [(s[z])-1][(s[z+1])-1];
y++;
}
for (z=0;z<n;z++)
printf ("%c", s2[z]);
return 0;
}
My problem is, that it this blows up if input more chars than I should. For example if my input is:
2 3
ABC
DEF
This works just fine.
But if I put:
2 3
ABC
DEFF
It give me a segmentation fold and stops the program. Keep in mind that I have a space before the "%c" in scanf so it's ignoring the "\n" and spaces I put in the input.
What can I do to stop that extra chars in the array from blowing up?
scanf("%d",&n);
int s[n*2];
This code tries to scan and convert whatever is left in the input after reading the matrix. If the input is not numeric, as will be the case if you enter more letters than the matrix should contain, the conversion will fail and n will remain uninitialized. Then int s[n*2]; is undefined because n is indeterminate.
If you want to ignore some characters in the input, you need to do so explicitly. You also better check return values of all functions that take user input, and verify that the values read are sensible.
Ok i figured out that the problem with it was input going to the buffer. To solve this i cleared the buffer before the next input using:
while (getchar() != '\n');
Your problem is filling the array over that size.
You get your input character by character and if you enter character more than your array size the program will stopped or has been logical error,
So you can use getche() and check the array constraint.
You can edit your code as follow:
int main (){
int nl, nc,i,j;
scanf ("%d %d\n", &nl,&nc);
char matrix [nl] [nc];
for (i=0;i<nl;i++)
for (j=0;j<nc;j++)
matrix[i][j]=getche();
(...)
return 0;
}
Use %s instead of %c and remove the inner loop. So the code will be something like this:
for(i=0; i<nl; i++)
{
scanf("%s", &matrix[i]);
}

Resources