I want to repeat a set of command in my C program. This will depend on the number that the user enters. For example: if user enters 3, the codes inside the while loop I have will repeat 3 times. Here is my code:
#include <stdio.h>
int main(void){
int num1,i,num2,num3;
printf("Enter your number:");
scanf("%d", &num1);
num1 = i;
while (i < num1) {
printf("Enter days");
scanf("%d", &num1);
printf("Hello World");
printf("Bye World");
}
}
When I run the program it just asks me the number to enter and then the program ends.
num1 = i;
i is just declared not initialized and you compare it in loop-
while (i < num1) {
Initialize i and then use it .
What you wrote in question and what you did is little confusion , but to make it work -
i=0;
//num1=i; I didn't get these parts so commented it
while (i < num1) { //you loop will run now
// printf("Enter days"); // these also didn't get it either
//scanf("%d", &num1);
printf("Hello World");
printf("Bye World");
i++;
}
You can use a while loop if you want, but using a for loop might make more sense and reduce the amount of code you need to write. I think that in this case the following would be reasonable:
#include <stdio.h>
int main(void){
int num1, i;
printf("Enter your number:");
scanf("%d", &num1);
for(i = 0 ; i < num1 ; ++i) {
printf("Hello World");
}
printf("Bye World");
}
Best of luck.
num1 = i;
while (i < num1) {
How it is possible, while condition will be false always. It should be like
i = 0;
while (i < num1) {
Rest all looks good.
Related
I just started learning C language. So, I am running into a lot of problems. I thought declaring i under for loop is enough, and I can use the value of i for outside too. But I think, that was not the case. Can someone explain the situation, please.
# include <stdio.h>
int main(void)
{
int x;
printf("Enter how many numbers in arrays you want to input : ");
scanf("%i", &x);
int score[x];
for(int i= 0; i <= x; i++)
{
printf("Enter the score : ");
scanf("%i", &score[i]);
}
// in the below line the output said "i" is undeclared.
float average = score[i] / x;
printf("The average score is : %f", average);
}
The answer is fairly simple
because of where you decalred i it is only visable to the for loop.
To make i visable to the whole function all you need to do is:
int i = 0;
for (; i <=x; i++){
printf("Enter the score : ");
scanf("%i", &score[i]);
}
this makes i avaliable throughout the function
i is declared in the initialization section of a for statement. That means the scope and lifetime of that variable is the expressions in the for statement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.
You need to declare i outside of the loop if you want to use it outside of the loop.
int i;
for(i= 0; i <= x; i++)
That being said, you don't actually need to use i outside of the loop.
There are security issues associated with using scanf so don't use it for anything serious. That said, I tried to re-write your program properly, and it still has pretty rubbish input validation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUTTEXTLEN 20
#define MAXINPUTINT 1000
int inputint() {
char inputtext[INPUTTEXTLEN + 1] = {0};
long inputval;
while (1) {
fgets(inputtext, INPUTTEXTLEN, stdin);
if (strlen(inputtext) > 0) {
inputval = atoi(inputtext);
if ((inputval < MAXINPUTINT) && (inputval >= 0)) break;
}
}
return (int)inputval;
}
int main(void)
{
int x = 0;
printf("Enter how many numbers in arrays you want to input : ");
//scanf("%i", &x);
while (x <= 0) {
x = inputint();
}
int score[x];
float average = 0;
for(int i= 0; i < x; i++)
{
printf("Enter the score : ");
//scanf("%i", &score[i]);
score[i] = inputint();
average += score[i];
}
average /= x;
printf("The average score is : %f\n", average);
}
I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
I have to take a university course on C and I shall read in some integers with a while loop. The code is:
#include <stdio.h>
#define max 100
int main(){
int a[max];
int i,n;
printf("Enter the number of persons: ");
do{
scanf("%i", &n);
}while((n < 1) || (n > max));
i = 0;
while (i < n){
printf("Enter the age of the %i th Person", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
/* further code */
It compiles (with the gcc compiler), but as soon as I get into the loop, it reads in the numbers correctly, but after the last input, nothing is executed anymore.
Initialise i
int i = 0;
int n;
[edit: I see now that you have edited your code as I suggested]
Initialize i = 0
Here is the working code.
#define max 5
int main()
{
int a[max];
int i = 0,n;
printf("Enter the number of persons:\n");
do{
scanf("%d", &n);
}while((n < 1) || (n > max));
while (i < n){
printf("Enter the age of the %i th Person:\n", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
return 0;
}
i has a garbage value at first you should write i=0 at first
and than scanf("%d", &n); Because you are calling a while loop with a garbage value of i at the beginning and code executes if the belove statistics satisfied while((n < 1) || (n > max)) but i has no value so you do not increment it. Think about sum,count I'm sure you know what i mean. if you want to increment something you should define first. An integer i defined with no value cant increment. Use for loop at last loop, instead of while
For my program I am trying to ask the user to insert a fraction then if they hit option 2 it will display those fractions. So far I figured out how to ask the user for a number and it stores that number, how ever I need the code to ask to enter a numerator then when I hit enter I would enter the denominator. I believe my code to view the numbers is written correctly however I need it to display fractions, which is what I am having difficulty with.
This is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int i = 0;
int num = 0;
while (num == 0) {
int num1;
printf("\nPress 1 to enter a the fraction\n");
printf("Press 2 view the fractions\n");
scanf("%d", &num1);
int num[100][500];
int n[100];
if (num1 == 1)
{
printf("Enter the numerator followed by the denominator\n");
scanf("%s", n);
strcpy(num[i], n);
i++;
}
if (num1 == 2)
{
printf("\n-----------------------------");
for (int j = 0; j < i; j++)
{
printf("\n%s\n", &num[j]);
}
printf("\n\n-----------------------------");
}
}
system("pause");
return(0);
}
I want a program that can get two integers from user and put the sum of those inputs in a variable, after that checks that is sum more than 5 or not ? (I know I can do it with if , ... but I want to do it with while). I myself did it but it has some problems, would you mind saying what is the problem and how can I debug it ? Here is my code :
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
}
return 0;
}
This line is only scanning for 1 integer (%i with a 2 format, indicating only take 2 digits.):
scanf("%2i", &ui1, &ui2);
But it seems you expected to receive two integers.
This will leave the second argument, ui2, uninitialized.
(It should fill ui1 successfully, at least)
Try instead:
scanf("%i %i", &ui1, &ui2);
Try including the scanf statement into the loop, it will no longer be an infinite loop... (also need to dereference the integers, see EDIT)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:\n");
//scanf("%2i", &ui1, &ui2);
int sum = 10;//(so that it will enter the loop at least once)
//sum = ui1+ui2;
while(sum > 4)
{
printf("enter number 1:\n");
scanf("%i", &ui1); //EDIT &
printf("enter number 2:\n");
scanf("%i", &ui2); //EDIT &
sum = ui1+ui2;
}
printf("result is: %d\n", sum);
getchar();//so you can see the result;
getchar();
return 0;
}
Actually while is a loop stmt not a conditional checker
if you want conditional checker use if...else series , switch etc
Note: in your code loop starts if (sum > 5) and never ends (infinate "Whats up !")
sum = ui1+ui2;
while(sum > 5) ///loop starts if (sum > 5) and never ends (infinate "Whats up !")
{
printf("Whats up !"); // (infinate "Whats up !")
}
if(sum > 5)
{
//greater stuff
}
else
{
//lower stuff
}
See Tutorial Here conditionals Stmts
You need to reset the "sum", because otherwise the while loop will be true FOREVER.
Second the input scanf is simply wrong.
Here the correct code
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%d %d", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 4) { printf("Whats up !");
sum=0;}
return 0;
}
I'm not sure that i got what you want to do... but if you simply want to check the sum of the two integers using the while statement, you can put a break inside the while loop and everything will work :)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
break;
}
return 0;
}
As others told you, using a if is the best solution