How could i continue this loop in C - c

I'm trying to output the same amount of printf statements in both loops and i have to use for and while . Unfortunately i get a endless loop for my second loop. What I'm i doing wrong in my second loop?
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main()
{
int x,c,v,b;
printf("Please enter a number between 1 and 25 \n");
scanf_s("%d",&x,&c);
for (x != 0; x--;)
{
printf("I'd rather be doing something else \n");
}
while (c!=0 ) {
printf("Programming is easy");
c--;
}
}

scanf_s("%d",&x,&c);
in this scanf you are getting only one value.
Here variable c is getting some garbage value and because of that it may be running for a long time which you are thinking as endless loop.
Use
scanf_s("%d %d",&x,&c);
As per as for loop syntax.
for(variable initialization; condition; variable update)
in your code you have already having value of variable x.
Condition checking x != 0
Variable update x--
so it should have to be
for( ; x != 0; x--)
EDIT:
How would i make the user prompt to enter a series of numbers until the user enters a -1 to stop.?
Simple code you can use is.
scanf("%d,&a);
while(a != -1)
{
//do work here
//
//
//-----
scanf("%d,&a);
}

Related

New input isn't asked, Inside a while loop in C

I have been trying to solve the problem set 1 in CS50, language C. I've come to this point, but I got stuck in here. I want my code to ask for a new input while(n>=9 || n<=0) but it ends there, instead of asking for a new input. I have already tried return n; but it didn't work at all. You can see the console and the results.
When I asked my code to return 0; I thought it would be asking for a new input. But as it can be seen, it ended up. What I want is it to ask for a new input, instead of stop working.
This is my first time and post in here, so I hope I have described my problem good enough.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Number: ");
while(n>=9 || n<=0)
{
return 0;
}
int i;
for(i=0;i<n;i++)
{
int a;
for(a=n-1;a>i;a--)
{
printf(" ");
}
int y;
for(y=0;y<=i;y++)
{
printf("#");
}
printf("\n");
}
}
As others suggested, return 0 is an action that terminates the current function you are in, and returns said value. I don't know what is your level of knowledge of C, I'll try to put less informations possible here. Just know that if you write return inside your main(){} block, the program will ignore all the following code and end the program if that return is executed.
Now as to how to get your desired result
I want my code to ask for a new input while(n>=9 || n<=0)
it seems you just need to put your statement inside the while loop:
int n=0;
while (n>=9 || n<=0)
{
n = get_int("Number: ");
}
in this case you need to declare int n outside the loop since you will use it later. (I initialized it as 0 to let the program enter the loop).
If you have studied and are able to use "do while" loops, it may be your best choice here. If your program needs to ask for input, and keep asking until input is no longer in the range (n >= 9 || n <= 0) you might want to try
int n=0;
do
{
n = get_int("Number: ");
} while (n>=9 || n<=0)
This will execute the block of code once for sure, then checks if the while condition is met and loops again. The outcome is you get the statement executed once and then until the condition is no longer met.
Put your code inside while loop to ask it whenever (n >= 9 || n <= 0) because right now whenever n is greater or equal 9 or less or equal 0 your your program will end because return 0 ends actual function and in your case it is main() function

How to solve uninitialized local variable used? [duplicate]

This question already has answers here:
uninitialized local variable 'j' used
(3 answers)
Closed 5 years ago.
#include <stdio.h>
int main() {
int x; int counter;
while (scanf_s("%d", &x) != 0)
{
puts("Enter the a signed number : ");
if (x % 2 == 0) { counter=counter++; }
}
printf(" %d pair numbers", counter);
}
I get
uninitialized local variable counter used.
The program is supposed to keep asking for numbers until it gets zero and tells us the amount of pairs given.
You need to initialize counter to 0 before trying to increment it. Also counter = counter++; is redundant (and undefined!). Just use counter++
The problem you are facing is cause by your use of the variable counter without initializing it. This is exactly what the compiler is telling you.
When you try to execute counter=counter++; for the first time, counter has no definied value. You might think by int counter; it gets initialized with 0, but this is wrong in C.
The next problem is the line counter=counter++; itself. If you want to increment counter, just use counter++. Depending on the compile you are using, the use of counter=counter++ should give you at least a warning. On my machine using Apple LLVM version 8.1.0 (clang-802.0.42) I get
warning: multiple unsequenced modifications to 'counter' [-Wunsequenced]
Then you try to loop until you read 0. But scanf() (use this instead of the Microsoft specific scanf_s()) does not return what it has read from stdin but the number of input items assigned. It returns 0 in the event of a matching failure.
So here is what to do:
Initialize counter
Replace counter=counter++ with counter++
Use another loop breaking condition than the return value of scanf()
One approach could be the following:
#include <stdio.h>
int main() {
int x=0;
int counter=0;
do{
printf("Enter the a signed number: ");
scanf("%d", &x);
if (!(x % 2)){
counter++;
}
} while(x);
printf(" %d pair numbers\n", counter);
}

Infinite loop due to wrong condition in C

Hey guys i'm new to C and i'm trying to learn something by myself.
So here's the question: i have an infinite loop and i don't understand why.
I've already checked other topics but i didn't understand, actually.
Here's the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int n,i=0; // the number of temperatures to analyse
scanf("%d", &n); fgetc(stdin);
char temps[257]; // the n temperatures expressed as integers ranging from -273 to 5526
fgets(temps, 257, stdin); // the n temperatures expressed as integers ranging from -273 to 5526
int temp[257]={0};
char *pointer;
pointer= temps;
while(*pointer != NULL){
int i=0, sign=1;
if(*pointer == '-'){
sign=-1;
pointer++;
}
while(*pointer != 32) { //infinite loop!
if(*pointer >='0' && *pointer<='9'){
temp[i]= (temp[i] *10) + ((*pointer) -'0');
temp[i]= temp[i]*sign;
printf("try");
}
}
printf("%d\n", temp[i]); //verifying temps != 0
pointer++;
i++;
}
return 0;
}
I really don't understand why.
Anyway, the aim of the program is: "Write a program that prints the temperature closest to 0 among input data. If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5)."
You may need it.
Thank you in advance.
In the loop:
while(*pointer != 32)
you never change pointer or *pointer within the loop body. So if this loop is entered once then it can never exit.
You probably meant to have a pointer++ somewhere, and perhaps the loop condition should actually be while(*pointer >='0' && *pointer<='9') (what if the string has some numbers, then a letter, then some numbers?)
However bear in mind that this loop will also have to check for end-of-string ('\0') and exit the outer loop correctly if it does hit that (instead of doing pointer++ and going past the terminator as you do in the case of the input being just -).
Ok, I actually understood. Thank you.
So now this is the loop
while(*pointer != 32 || *pointer != '\0') {
if(*pointer >='0' && *pointer<='9'){
temp[i]= (temp[i] *10) + ((*pointer) -'0');
temp[i]= temp[i]*sign;
pointer++;
}
}
Now it gives me values, but at a certain point, it becomes infinite.
The rest of the code is the same.
EDIT: i modified the loop condition with while(*pointer >='0' && *pointer<='9') and it's not infinite!
But doesn't work. There may be a logical mistake.
EDIT 2: i found it. i've initialized i=0 in the while loop and of course it kept updating the same temp[i].
Thank you again.

What is this code running infinitely in 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.

C function call as test condition

Few days ago I've a weird idea came into my mind that manipulate if(); statement in a weird way.Let's go on to a simple code.
The Code :
if(printf("blahblah\n");{
}
My Idea :
1.)To me I think this code will always evaluated to be true(my assumption) since the test condition is substituted with a function call.
So today I'm doing an exercise provided by a book(just to help me refresh what i learn few days ago).This is the code.
The Code :
#include <stdio.h>
int main(void) // This program would add up the value enter by user , for e.g with the
{ //input of 20 , it will print out the sum of 1+2+3+4+5.....20.
int count , sum , size;
count = 0;
sum = 0;
printf("Enter a value to find the sum of it from 1 : ");
scanf("%d" , &size);
while (count++ < size)
sum = sum + count;
printf("sum = %d\n" , sum);
return 0;
}
By using my idea on the first code , I modified the second code into this.
#include <stdio.h>
int main(void)
{
int count , sum , size;
count = 0;
sum = 0;
printf("Enter a value to find the sum of it from 1 : ");
while (scanf("%d" , &size) && count++ < size )
sum = sum + count;
printf("sum = %d\n" , sum);
return 0;
}
The Question :
1.)Based on the assumption made by me in the first code , the scanf() function suppose to be always evaluated to true.That's why the second test condition count++ < size is the one that determine whether the statement in while statement will be executed or not.
2.)But when I run the program , I input 30 but it doesn't work , the program just stop there without doing anything after i hit enter.
3.)I try to switch the to test condition with the `count++ < size as left operand while the input function as right operand.
4.)After doing so , the result i get is different.When i try to run the program , the program execute the second printf() function statement , and print out sum = 0.
Your help is much appreciated , do correct me for mistakes.I'm willing to learn from it.
To me I think this code will always evaluated to be true(my assumption) since the test condition is substituted with a function call.
This is incorrect. The function (in this case, printf) returns a value (in this case, an int). When you use it as the condition in the if statement, the function is called and the value it returns becomes the condition: if it returns zero it evaluates to false; if it returns nonzero it evaluates to true.
There is no difference between
if (printf("Hello, World!")) { }
and
int i;
i = printf("Hello, World!");
if (i) { }
(aside, of course, from the additional variable in the second example.)
In your modified second example, scanf is called each time the loop condition is checked. You could rewrite the loop like this:
while (1)
{
int result_of_scanf;
result_of_scanf = scanf("%d", &size);
if (result_of_scanf == 0)
break;
if (count++ >= size)
break;
sum += count;
}
scanf doesn't just get called once; it gets called for each iteration of the loop. scanf returns the number of elements that it read successfully, so in this case it will return either 1 (if you input a valid integer within the range of int) or 0 (if you give any other input).
The program appears to be stuck but actually it is expecting you to input numbers. That is you will have to enter numbers till the count is equal to the input number.

Resources