Basic addition loop c - c

I'm trying to write a code which adds a value - say X - to a user entered int, and continues to allow the user to add further int values to 'X+all previously entered int values' until a value of 21 or greater is reached - where the code exits the loop. I thought it would be a simple case of value=value+X but I'm going wrong somewhere...
void additionFunction()
{
int j=0;
int tot;
//tot=cat.firstCard+cat.secondCard; is the actual tot value but for simplicity;
tot=5;
for(j=0; j+tot<22; j=j+tot)
{
printf("Enter next card\n");
scanf("%d",&j);
}
}
I know this is a very simple question but I'm stuck as to what else to try. It was originally implemented in a if,do,switch loop in the shortened form;
if(cat.firstCard!=11 && cat.secondCard!=11)
{
do
{
switch(tot+j>=4 && tot+j<=8)
{
printf("Hit\nEnter next card\n");
scanf("%d",&j);
break;
}
switch(tot+j==9 && (cat.dealersCard==2 || (cat.dealersCard>=7 && cat.dealersCard<=11)))
{
printf("Hit\nEnter next card\n");
scanf("%d",&j);
break;
}
...
switch(tot+j>=17 && tot+j<=21)
{
printf("Stand\n");
j=50;
break;
}
switch(tot+j>21)
{
printf("Bust\n");
j=50;
break;
}
}while(j!=50);
}
else //etc.
This method didn't work either. I know this is simple but I can't find the answer anywhere. It would be great if you could answer for the second case but any answer is appreciated!
only use stdio.h, no global variables

You need to increment tot rather than j. I think it could be clearer like this:
void additionFunction(void)
{
int tot = 5;
while (tot < 22)
{
int j;
printf("Enter next card\n");
if (scanf("%d", &j) != 1)
break;
tot += j;
printf("Read: %d - total = %d\n", j, tot);
}
}
I've kept your variable names, but they could be improved (tot ⟶ total; j ⟶ value, perhaps). I added the second printf() to identify what's going on better (but there's room to improve that, too, though a debugger could also be used to see the information). I suspect you will need to do more work in the loop, or return a value from the function, but this is OK as an MCVE (Minimal, Complete, Verifiable Example).

The problem is you are resetting j every time in the loop with user's input with this line - scanf("%d",&j);
This should fix it, by assigning input into another variable and add it to j.
int j=0,input,tot=5;
for(j=0; j+tot<22; j=j+input)
{
printf("j=%d tot=%d\n",j,tot);
printf("Enter next card\n");
scanf("%d",&input);
}

Related

C Loop until the condition is met problem

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

Partial array output includes garbage

Most of my experience is limited to SQL scripting for DBA functions. I am a security specialist and provide help to others on those topics, but I am learning C to aid in those other endeavors. I've been reading books, writing small programs, and expanding the difficulty level as I go. This is the first time I've had to reach out for help. I apologize if this has been asked, but I did search first and didn't find anything.
So far, my programs have always returned only the valid data from partially filled arrays. This particular one is not behaving the same even though I'm using the same for statement I have previously used with success. At this point I must have tunnel vision because I cannot seem to see where this is failing.
If there are fewer than 20 inputs, the printf output displays the remaining values with garbage. It would be greatly appreciated if someone could provide some guidance on what I'm overlooking. Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct grade
{
int id;
int percent;
};
#define maxCount 100
int main()
{
int *grade;
struct grade gradeBook[maxCount];
int count = 0;
char YN;
int i;
for(i = 0; i < maxCount; i++)
{
printf("Enter ID: ");
scanf("%d", &gradeBook[i].id);
printf("Enter grade from 0-100: ");
scanf("%d", &gradeBook[i].percent);
count++;
// Prompt to continue, break if done
printf("Do you want to Continue? (Y/N)");
scanf(" %c", &YN);
if(YN == 'n' || YN == 'N')
{
break;
}
}
void sort(struct grade gradeBook[],int cnt)
{
int i, j;
struct grade temp;
for (i = 0; i < (cnt - 1); i++)
{
for (j = (i + 1); j < cnt; j++)
{
if(gradeBook[j].id < gradeBook[i].id)
{
temp = gradeBook[j];
gradeBook[j] = gradeBook[i];
gradeBook[i] = temp;
}
}
}
}
printf("Grades entered and ordered by ID: \n");
for (i = 0; i < count; i++)
{
printf("\nID:%d, Grade: %3d\n", gradeBook[i].id,gradeBook[i].percent);
}
return 0;
}
If there are fewer than 20 inputs, the printf output displays the remaining values with garbage
What else did you expect?
If you have fewer than 20 inputs, then the remaining inputs have not been given any value. You say "partial array input" but you literally asked the computer to loop over the entire array.
It's really not clear what else you expected to happen here.
Perhaps loop to count the second time instead.

Undefined reference error to function that is actually defined in C

I wrote this program to build a number diamond. The issue is that when I compile the program, it throws the error
build2.c:(.text+0x5): undefined reference to `get_input'
collect2: error: ld returned 1 exit status
I've tried for hours to figure out what exactly the problem is (e.g. if there is a spelling mistake or something similar), but the function call looks identical. I have attempted to rename it, write it as both a prototype and as an implementation, and nothing seems to work. Is there an issue that I'm not seeing?
//Define prior to main
int is_valid(int);
int get_input(void);
void print_pattern(int);
//Main
int main(void){
int diamond_size;
//diamond_size = get_input();
//value from get imput method used for diamond size
print_pattern(get_input());
return 0;
}
void print_pattern(int size){
int length, num, i, j;
//beginning of new diamond
printf("\n");
//Define each integer to work in layout of diamond
//First for loop fans out
for(i=1; i <= size; i += 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
//second for loop fans in
for(i=size-2; i >= 1; i -= 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
int is_valid(int value){
int rem;
//uses remainder to determine if it is odd or even; an even number will not have a reaminder in this case
rem = value % 2;
if (rem == 0){
printf("You've entered a even number. Please try again.\n");
return (0);
}
//greater than 9 cnd
if (value > 9){
printf("You have entered a number greater than 9. Please try again.\n");
return (0);
}
//less than 1 cnd
if (value < 1){
printf("You have entered a number less than 1. Please try again.\n");
return (0);
}
return (1);
}
int get_input()
{
int cont, number, valid;
cont = 1;
while (cont = 1)
{
printf("Enter an odd number less than 9 and greater than 0 < ");
scanf("%d", &number);
valid = is_valid(number);
if (valid == 1)
{
cont = 0;
}
}
return number;
}
}
You seem to have nested functions; this is (a) a non-standard GCC extension, and (b) I presume the scope of the nested get_input() function is the enclosing function, not the file scope. The solution is to move get_input() to file scope. At the end of print_pattern() add an extra }, and delete the final } at the end of the file.
Also, please format your code - most IDEs these days have options to tidy it up, and with correct indentation you may have seen your problem earlier.
Oh, and as a bonus bug fix, you also have in get_input():
while (cont = 1)
This will always be true - use this instead:
while (cont == 1)
The function print_pattern is not terminated at proper place but instead at the very end of the file:
void print_pattern(int size){
...
... end of the loop
}
... more functions
...
... end of print_pattern
}
This results into defining nested functions instead of global level.
It's generally good habit to indent the blocks, in which case you would realized the mistake very quickly.

adding an outer while loop to my c program - beginner 1 to continue 0 to stop

This is my first post on stack overflow, so this is my code so far, i'm just starting computer engineering and am having some trouble.
#include <stdio.h>
int main ( void ) {
int num, sum = 0, i, ssq = 0, isq, n;
printf("Enter an integer: ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
sum = sum + (i * i);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
while (i >= 0) {
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
printf("Enter an integer: ");
scanf("%d", &num);
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
if (i == 0) break;
}
return 0;
}
This is what I have so far believe it or not it took me 12 hours to do the first part, I've literally been up all night working on this, before the while loop and now I'm completely lost. I added the ssq=0, isq, and n ints in to try to help with no avail. At this point I'm just rearranging stuff for hours on end, this is my first post so please don't be too hard on me!
This contains a whole host of errors, from typos to code duplication, as #HappyCoder has noted above.
First of all, the outer part and the loop part do exactly the same. Think about it for a moment. You first do some task, unconditionally, then ask the user if they want to start over. The task itself doesn't change! Hence, what we can do is this:
do the task;
ask the user if they want to quit or go on;
if yes, return to the start.
In code, this can be done with an endless loop that you break out of if the user wants to stop:
while(1) {
// do user input and calculations here;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
if (i == 0)
break;
}
See, now we only have one instance of the calculation code! Now, you can throw away half the variables declared in the beginning, since they are duplicate.
Now on to the calculations. You have an uninitialized variable, ssq, in the loop. See where code duplication can get you. In the outer part, it is initialized properly. Inside the loop, however, it is not guaranteed to hold any concrete value, most likely it contains garbage.
Also, as noted by #JohnHascall, this subtle error introduced most likely by a typo:
for (isq = 1; isq <= n; isq++); // <---- the evil semicolon
ssq = ssq + (isq * isq);
The semicolon after the for loop makes the loop empty, and the summation only happens once, but not in the loop, as you want it to be.
Then, you output (print) sum not ssq inside the loop, which is obviously not what you want to print. And, you use the uninitialized n variable from outside the loop as the boundary, instead of the user inputted num.
I want to add yet one more. Sanely naming the variables is a big deal as it helps you to catch potential errors and keep track of how variables are being used throughout the code, not to mention easier understanding of the code by others. Look: int i -> int choice better isn't it?
So we can rewrite the code like this:
#include <stdio.h>
int main ( void )
{
int boundary, choice, isq, ssq;
while (1) {
printf("Enter an integer: ");
scanf("%d", &boundary);
ssq = 0;
for (isq = 1; isq <= boundary; isq++) {
ssq = ssq + (isq * isq);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", boundary, ssq);
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
if (choice == 0)
break;
}
return 0;
}
for (isq=1; isq<=n; isq++);
ssq = ssq + (isq*isq);
The problem here is that 'n' is not initialized and not used in above scanf statement, you need to use 'num' instead of 'n'
for (isq=1; isq<=num; isq++)
ssq = ssq + (isq*isq);
One likely problem is here:
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
You probably want:
for (isq = 1; isq <= n; isq++) {
ssq = ssq + (isq * isq);
}
Also, you should add:
ssq = 0;
above that loop (think about your 2nd trip through the loop).
Here is #iksemyonov 's answer refactored to honor the "no more than 7 lines in a method" rule (using a hard and fast arbitrary number like 7 is absurd, but the principle of making function do a specific understandable task is reasonable).
#include <stdio.h>
static int getBoundary ( void ) {
int boundary;
printf("Enter an integer: ");
scanf("%d", &boundary);
return boundary;
}
static int computeSSQ ( int limit ) {
int ssq = 0;
for (; limit > 0; --limit) ssq += (limit*limit);
return ssq;
}
static int again ( void ) {
int choice;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
return choice;
}
int main ( void ) {
do {
int boundary = getBoundary();
int ssq = computeSSQ(boundary);
printf("The sum of the squares of integers from 0 to %d is %d\n",
boundary, ssq);
} while (again());
return 0;
}
You have made a few mistakes here:
You have put a semicolon after the for loop inside the while block which should be removed.
Inside the while block you have accepted value for 'num' while you have used 'n' in the for loop (for which value is uninitialized). So you should accept the value of 'n' instead of 'num' or else replace 'n' in the for loop with 'num'.
If you want to exit the while loop immediately after user inputs 0 then move the if (i == 0) break; statement to below the scanf ("%d", &i) statement.
In the printf() statement next to the for loop, you have used value of 'sum' while you have calculated value for ssq.
Also you should write ssq = 0 after the printf() statement to reset its value to 0.
Correct all these and the program will work.
what you want to do was basically a menu driven program... i would suggest , like the above one's are right too... but another way you can do is using do{
//the task , i.e. the sum
} while(i!=0);
doing this since do while is an exit controlled loop as you might be knowing... so as in earlier stages u can be free from using break; keyword...
also as you are starting an early bird tip i would like to give is that the suggestion of using functions by #John above ....is good but not if you are doing mistakes in a normal int main() 15 lines code... since if you go in user defined functions like stated above you might go wrong in passing the arguments or basics of function passing... so go for a normal int main code for now...
Note i didnt meant that what # John said was wrong or something...just gave my view/advice

Using getNum(); Properly and Infinite Loop Problems

Just having a few kinks in this assignment I'm trying to do. Basically I need to have a menu, 4 options, two of them accept input from user as the form of a base number and an exponent. The third one outputs the answer of the base raise to the power and then the fourth just exits the program.
I'm having trouble obtaining the users input via getNum(); I'm not too sure how to use it properly. Just looking on some tips on how to make my code work a little better.
Looking for Help:
Accepting user input from two different functions and using it to
output an answer
Working out the infinite loop problem when selecting menu option
Loop back program to main menu after each function is done and only
exit program when menu option 4 is selected
int main(void)
{
int option = 0;
do
{
loadMenu();
while (option<1 || option>4)
{
printf("\nChoose an option between 1 and 4:");
option = getNum();
while (getNum() != '\n');
}
switch (option)
{
case 1:
baseChange(); //Gets base number
break;
case 2:
powerChange(); //Gets exponent
break;
case 3:
calcMath(); //Calculates the answer
break;
default:
break;
}
}
while (option != 4);
printf("Goodbye!\n");
}
void loadMenu() //Menu choices
{
printf("Power Menu:\n" );
printf(" 1. Change base\n");
printf(" 2. Change exponent\n");
printf(" 3. Calculate\n");
printf(" 4. Exit\n");
printf("Option?\n");
}
int baseChange(int base)
{
printf("What is your base?: ");
base = getNum();
while (getNum() != '\n');
return base;
}
int powerChange(int power)
{
printf("What is the power?: ");
power = getNum();
while (getNum() != '\n');
return power;
}
int calcMath(int base, int power)
{
int index = 0;
long answer = 1.00;
for(index = 1; index <= power; index++) answer = answer * base;
{
printf("%d raised to the power of %d is %ld.\n\n", base, power, answer);
}
return answer;
}
I'm having trouble obtaining the users input via getNum(); I'm not too
sure how to use it properly.
You haven't told us anything about this function; it's not part of the C standard.
Just looking on some tips on how to make my code work a little better. Looking for Help:
I think it's a little early for that. Put more effort into solving your problems, and then come back if you have specific questions. More like this one:
Working out the infinite loop problem when selecting menu option
Look at what your program does with option the second time through the loop.
Please Declare the getnum() function before main() like below;
/* declare getnum() prior to its first use */
float getnum(void)
{
float x;
printf("Enter a number: ");
scanf("%f", &x);
return x;
}

Resources