What is this code running infinitely in C? - c

In this program:
#include<stdio.h>
int a[5],c=0;
int main()
{
printf("Enter no\n");
scanf("%d",&a);
for(int i=0;a[i];i=+2) {
printf("%d ",a[i]);
}
return 0;
}
I want to input 12345 and get the output 1 3 5, but the program never terminates. How can i do this?

Honestly, your code is just all over the place, it looks as if you're just wildly guessing:
You can't pass an int array to scanf(), ask it to read one int, and expect it to put all the digits of a multi-digit number into the individual elements all by itself like that. You either need to read in a string, or read in a single int and extract the digits yourself.
The variable c is unused.
Your for loop makes no sense at all. Even if you had filled all the elements of your array a, it still wouldn't make sense, and you haven't.
Here's a sensible version of your code, reading into a string:
#include<stdio.h>
int main(void) {
char a[6];
printf("Enter no\n");
fgets(a, 6, stdin);
for (int i = 0; i < 5; i += 2) {
printf("%c ", a[i]);
}
putchar('\n');
return 0;
}
with output:
paul#local:~/Documents/src/sandbox$ ./num
Enter no
12345
1 3 5
paul#local:~/Documents/src/sandbox$
Note that this does nothing to check whether the user actually did enter five characters, which your program should do.

the for loop is defined in this way
for(initialization ; condition check ; variable update)
in your code
for(int i=0;a[i];i+2)
{
printf("%d ",a[i]);
}
the condition part of the for loop is set to a[i], which is probably never false. so the loop runs infinitely. the variable update is also incorrect. i value should be updated.
try
for(int i=0; i<5; i+=2)
{
printf("%d ",a[i]);
}

The code is running infinitely because nothing changes inside the loop that would cause the loop to terminate. No variable's value is changed anywhere inside the loop. If a[i] is true for the first iteration, it will remain true forever since i's value never changes.

Related

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.

Can someone help me understand the execution of this C program? (Beginner)

#include <stdio.h>
main()
{
int a[2][5], i,j; //2d array declaration
for(i=0;i<=1;i++) //first loop for 1st dimension
{
for(j=0;j<=4;j++) //nested loop for 2nd dimention
{
printf("Value for a[%d][%d] is : ", i,j);
scanf("%d", &a[i][j]); //asks for value
}
}
}
In this program, when the loop is executing, in the first run, i=0, and inside that j=0,1,2,3,4.
When this is done and it comes to the 2nd dimension where i=1, why does it run the nested loop again when the condition is already false (j<=4)?
Where are all these constant values saved? Does it restart the value of j when the nested loop is run again?
A for loop has three components (expressions) in the form for (A;B;C):
A - Pre-Iteration, run once at the start
B - Loop Condition, tested before each iteration, including the first
C - Post-Iteration, executed after each iteration
You're asking to initialize j=0 each time the loop starts, then testing j <= 4 which will be true. When the loop repeats it does j++, then tests again.
It's worth noting that these are all optional and for (;;) is valid, but is an infinite loop unless you break it.
With minor improvements:
int main(void) //added int and void to main
{
int a[2][5], i,j; //2d array declaration
for(i=0;i<2;i++) //first loop for 1st dimension
{
for(j=0;j<5;j++) //nested loop for 2nd dimention
{
scanf("%d", &a[i][j]); //asks for value [note, before printf]
printf("Value for a[%d][%d] is %d\n: ", i,j, a[i][j]);
}
}
return 0;//int main(void) requires a return statement
//Note also, 'main()' is really not a proper signature for
//the main function
}
This code intends to assign values to each member of the 2D array by using prompted input values using scanf, but because of some syntax and logic errors, the original would not work as intended. To help, the order of the two lines in the nested for loops has been switched to prevent the array from being accessed before being initialized.
The nested for loop indexes have been modified in this version to use the same values for limit, as those used to size the array in its declaration:
int a[2][5];
for(i=0;i<2;i++)
for(i=0;j<5;i++)
scanf() is the method used for user input. Each call prompts for a value, which is placed into the corresponding row-column index indicated by i and j, and written to stdout. Note the actual value in the original code is not printed out, but it is in this slightly modified version.
The value of j is initialized to 0 each time you run the nested loop because you set the initialize expression of the for statement to "j=0"
That expression will be run for each execution of the outer loop

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

printing values of dynamic array

I have made a dynamic array of integers in C, here is my code
#include <stdio.h>
int main(){
int count=0, i, input;
int *myarr;
myarr=(int*)malloc(4*sizeof(int));
while(1){
scanf("%d", &input);
myarr[count]=input;
count++;
if (input == -1) break;
}
for (i=0; i<count; i++){
printf("%d ", myarr[i]);
}
return 0;
}
From the code, I thought i clearly made an array of 4 integers only i.e myarr[0] up to myarr[3], how come when i insert even 10 integers, it still prints all of them, it doesn't print garbage as i thought it would after the fourth integer... Maybe i didn't understand the point of dynamic creating an array?? Make me straight please!
You should only access myarr[0] up to and including myarr[3].
Accessing any other index is undefined behaviour: it might work, it might not.
Also, myarr[count]==input looks like a typo. Did you mean myarr[count] = input? The way you have it is testing if myarr[count] equals input. Technically the way you have it is undefined behaviour for any element of myarr since you are making use of uninitialised data.

Recursion to calculate sequence

Suppose that the first integer is x. Then we define a[0]=x, the next elements of sequence are calculated as:
a[n+1]=a[n]/2 if a[n] is even, and
a[n+1]=a[n]*3+1 if a[n] is odd.
The sequence continues till it reach value 1, then stop.
It looks like this 75, 226, 113, 340, 170, 85, 256, 128, 64, 32, 16, 8, 4, 2, 1
This is my code (not using the recursion). The proplem is that it keeps printing output=1 all the times. I have checked it but I don't know where I was wrong.
Another question is, which datatype is the best to declare for variable x and array a[] (to minimize to the least capacity ? And how can we do this with recursion ?
int main(void)
{
float a[100];
int i=0;
float x;
printf("Enter the value of x: ");
scanf("%f",&x);
a[0]=x;
printf("\n%f\n",a[0]);
do{
if (fmod(a[i],2)==0){
a[i+1]=a[i]/2;}
else{
a[i+1]=a[i]*3+1;
}
i++;
} while (a[i]!=1);
printf("The ouput value is:\n");
for (int j=0;j<i;j++){
printf("%2.2f\t",a[i]);
}
getch();
return 0;
}
The proplem is that it keeps printing output=1 all the times
Of course, since you always output the number after the last one in the array (your program even has undefined behavior).
Another question is, which datatype is the best to declare for variable x and array a[] (to minimize to the least capacity ?
Both could be an unsigned long long, you don't even need an array.
char buf[0x100];
fgets(buf, sizeof(buf), stdin);
unsigned long long n = strtoull(buf, NULL, 10);
while (n > 1) {
printf("%ull\n", n);
n = n % 2 ? 3 * n + 1 : n / 2;
}
You just do all the calculation in a single while loop with recursive way... replace this part of your code...
printf("\n%f\n",a[0]);
do{
if (fmod(a[i],2)==0){
a[i+1]=a[i]/2;}
else{
a[i+1]=a[i]*3+1;
}
i++;
} while (a[i]!=1);
printf("The ouput value is:\n");
for (int j=0;j<i;j++){
printf("%2.2f\t",a[i]);
}
replace it with something like that....
while(a[i] > 1){
printf("\n%f\n",a[i]);
if(fmod(a[i],2)==0){
a[i+1]=a[i]/2;
}else{
a[i+1]=a[i]*3+1;
}
i++;
}
I didn't test it but the main idea of recursion for this problem should be something like that if you do not want to use any external function for the calculation.
This recursive way also fixed the always printing 1 problem. As i see you already got your answer about printing 1 all the time in your code. You can use a long int instead of a floating point array. I think this ia a good idea. Then you have to change the code by replacing the array a[i] and a[i+1] to a int variable.
Sorry for my bad english. English is not my native language.
Thanks.
One part of your problem,
The proplem is that it keeps printing output=1 all the times
printf("The ouput value is:\n");
for (int j=0;j<i;j++){
printf("%2.2f\t",a[i]); //<--- use a[j] to print instead of a[i]
}
The reason it always prints 1 is you used the wrong variable in your for loop
for (int j=0;j<i;j++){
printf("%2.2f\t",a[i]);
}
You should access a[j] not a[i]. i is constant in the loop. You should change it to
for (int j=0;j<i;j++){
printf("%2.2f\t",a[j]);
}

Resources