a.) (function 1) take user input and decrement the value until userNum = zero
b.) (function 2) take the original user input and have zero increase by +1 until reaching said user input.
therefore, the output would look like this:
Please enter a positive integer: 5 (enters 5)
5
4
3
2
1
0
(four asterisks)
0
1
2
3
4
5
My problem is, I cant figure out how to set the original input for userNum in place so I can all it in the "loop_up_to_int" function. Any help would be appreciated, thank you.
#include <stdio.h>
int loop_down_to_zero(void);
int loop_up_to_int(void);
int main(int argc, char * argv[])
{
int userNum;
printf("Please enter a positive integer: ");
scanf("%d", &userNum);
//printf("%d\n", userNum);
loop_down_to_zero();
loop_up_to_int();
return 0;
}
//definitions here
int loop_down_to_zero() {
//scanf("%d", &userNum); do i scan for input here?
while (userNum >= 0) {
printf("%d\n", userNum);
userNum = userNum - 1;
}
printf("****\n");
}
int loop_up_to_int() {
int newNum;
int userNum;
newNum = 0;
printf("%d\n", newNum);
while (newNum != userNum)
{
newNum = newNum + 1;
printf("%d\n", newNum);
}
}
error message:
daily08.c:58:14: error: 'userNum' undeclared (first use in this function)
while (userNum >= 0) {
Your error message is because userNum doesn't exist in the function. It's only declared in main. Passing values is the solution.
You can pass values into functions (a core idea behind programming; variables shouldn't be global). Similar to how main has int in it's declaration; update both your functions to take a variable:
int loop_down_to_zero(int number)
Don't forget to update the function definition on top of your program also.
And you call the function by simply saying loop_down_to_zero(userNum). What you entered can now be accessed via number in each function, and userNum will stay intact in main().
Side note: When functions are done, they can return a value back to the caller. In your case you don't do that (nor do you need to). Both your functions should show they don't return anything, which is marked by using void i.e. void loop_down_to_zero(int number). Again remember to update the top of your program also.
Related
I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .
My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.
`
#include <stdio.h>
#include <stdlib.h>
// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
int warning(int num , int n, int count){
int check = count - 1 , array[n];
if(count <= n){
array[check] = num;
}
if(count == n){
alertwarning(array);
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
return 0;
}
int main(int argc, char *argv[]) {
int num, count, n;
printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");
printf("\nIntroduce how many warnings are being stored: ");
scanf("%d", &n);
fflush(stdin);
int array[n];
do{
printf("\nIntroduce a value equal or bigger then 0: ");
scanf("%d", &num);
fflush(stdin);
//system("cls");
if(num < 0){
printf("|Please introduce a valuer equal or above 0!|\n");
system("pause");
}
else if(num >= 0){
count++;
}
warning(num, n, count);
}while( count < n);
return 0;
}
`
I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.
how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.
I've tried so many different things but cant organize the structure properly to get the game actually working
I have the shell and functions layered out, but cant properly implement my defined functions into the sections where they are needed.
#define ROUNDS 3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void greeting();//display welcome message to user
int playRound(int round); //play one round
int humanPick(); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
int main()
{
void greeting();{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
for(int x = 0; x < ROUNDS; ++x)
{
int result = playRound(x + 1); //call playRound and assign result the value function returns
void winnerAnnouncement(int user){
if (user == )
}
}
printf("********************************************************\n");
printf("Thank you for playing!\n");
return 0;
}
int playRound(int round)
{
printf("Welcome to a new round %d!\n", round);
printf("You may go first!\n");
int toothpicks = 31; //number of toothpicks to start with
//int taken;
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
}
//loop that keeps track of toothpicks until respective no more toothpicks left.
while(toothpicks != 0)
{
printf("There are currently %d toothpicks left.\n", toothpicks);
printf("How many toothpicks are you going to take off the table?");
printf("Pick a number between 1 , 2 , and 3.\n");
scanf("%d", &userChoice);
int humanPick()
{
if (userChoice >= 1 && userChoice <= 3)
return userChoice;
if(userChoice < 1 || userChoice > 3)
return 0;
}
int computerPick(int choice, int leftover)
{
if (toothpicks > 4)
choice = 4 - leftover;
if (toothpicks = 2 || 3 || 4)
choice =
if (toothpicks = 1)
choice = toothpicks;
}
return toothpicks; //terminates loop
}
return 0;
}
You do not want to be defining functions inside of other functions. Although some compilers allow that as an extension, it is not part of the language. But, even if you are using a compiler that allows it, your syntax is wrong. Consider:
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
In the body of another function, the semi-colon after int taken) ends the declaration of the function, and the {...} after that is not a function definition but is just a block of commands to be executed in the enclosing function. You want to write this (outside of any enclosing function) as:
int
leftOnTable(int toothpicks, int taken)
{
...
}
and then call it as:
int
main(void)
{
...
int toothpicks = 31;
int taken = humanPick();
...
toothpicks = leftOnTable(toothpicks, taken);
...
}
Your attempt to define humanPick() seems incorrect. Getting user input is notoriously difficult, and scanf is almost always the wrong tool. (See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). By "almost always", I am being conservative and I actually mean that it is absolutely never the right choice. But, if you want to use scanf, you might try something like:
int
humanPick(int toothpicks)
{
int userChoice;
printf("There are currently %d toothpicks left.\n", toothpicks);
puts("How many toothpicks are you going to take off the table?");
puts("Pick a number between 1, 2 and 3.");
int rv;
while( 1 != (rv = scanf("%6d", &userChoice))
|| userChoice > 3 || userChoice < 1 )
{
char *msg = "Invalid input.";
switch( rv ){
case EOF:
puts("Terminating. Thanks for playing!");
exit(0);
case 1:
msg = "Choice must be 1, 2, or 3";
/* Fall thru */
default:
fprintf(stderr, "%s. Try again\n", msg);
while( (rv = getchar()) != EOF && rv != '\n' ){
;
}
}
}
return userChoice;
}
Be aware that this function changes the function prototype, and this version take toothpicks as a parameter.
Note two things about the usage of scanf here that are absolutely essential. You must always check the value returned by scanf, and you must always use a width modifier on the conversion specifier in the format string. If you do not understand what this means, you should stop using scanf. Without a width modifier, the behavior is undefined for certain inputs. Note that using a width modifier on %d means that you cannot reliably scan the full range of values that can be stored in an integer, and this is just one more reason to avoid using scanf.
"but cant organize the structure properly"
This section will work the way you have it, but I would place the #define below the #includes:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define ROUNDS 3
Your prototype section looks okay, but its idiomatic in declarations to use (void) rather than ()
void greeting(void); //display welcome message to user
int playRound(int round); //play one round
int humanPick(void); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
The highest number of compile errors have to do with using nested functions. The C language does not support them, and it is not a good idea IMO to use extensions that allow them. The form of the program should be shaped like this:
int main(void)
{
// declare variables and call functions here
greeting();
//other constructs & function calls here.
return 0;
}
//Functions definitions should include 1 definition for each prototype:
void greeting(void)
{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
int playRound(int round)
{
//content here (but your current content has issues)
return something;
}
int humanPick(void)
{
//content here
return something;
}
int computerPick(int choice, int leftover)
{
//content here
return something;
}
...and so on.
Note also I see you are using = to do comparisons. = is an assignment operator, for example toothpicks = 2 means assign the value 2 to the variable toothpicks. If you want to check equality, then use ==, eg if(toothpicks == 2){do something}.
An additional general note about function implementation and usage. Functions are seen in different forms:
prototype - is a declaration in the code that instructs the compiler about the data type of the function, arguments and parameter list. example: int add(int a, int b);
definition - The signature of a function is presented in the same way as that of its prototype but includes {...} enclosures which contain the body of executable code the function is designed to execute during run-time. Example:
int add(int a, int b)
{
return a + b;
}
calling a function - When a function is called, its signature, including the decorations around its name are not shown, but instead contain objects that are of the same type as specified in the function formal signature. For example, inside main(), or some other function:
int sum = 0;
int a = 10;
int b = 20;
sub = add(a, b);
Keep in mind that syntax errors will always be flagged by a good compiler, and prevent an executable from being created. But the number and type of warning messages you see at compile time is settable, and depend to some extent on how you have your compiler set. Setting the warnings on your compiler to a strict enough setting will output messages to warn of syntax errors, or possible mis-use of operators, or regarding function definition / usage and often suggest how to correct. if using GCC for example set compiler to use -Wall.
I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.
I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs
scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2
I have been coding the battleship game in C but I have a few problems. First of all, I would like to have a counter for the "hit and sunk" ships (it is coded, but it doesn't seem to work, after you hit a ship, it always prints 1), and therefore, this doesn't end the program when all ships are sunk. Here is my code for the main and "shoot" functions:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define rows 5
#define columns 5
int mainint main(){
srand(time(NULL));
int grid[rows][columns], attemps=0, ships;
int sunk;
printf("Let's play the battleship game!\n");
printf("You have 20 tries.\n");
printf("Enter the number of ships: ");
scanf("%d",&ships);
prepare_grid(grid); //Prepare grid with items of value -1
gen_ships(grid,ships); //Generate random ships surrounded by water (value 1)
print_grid(grid); //Print grid without showing the generated ships (all items will be "~" meaning "undiscovered water).
sunk=0;
for (int a=0;a<20;a++){
shoot(grid,sunk,ships);
attemps++;
print_grid(grid);
printf("\nAttemps: %d\n",attemps);
}
print_secret_grid(grid); //Print final grid, showing all sunk ships and positions shot
return 0;
}
void shoot(int grid[rows][columns], int sunk, int ships) {
int x, y;
printf("\nLine --> ");
scanf("%d", &x);
printf("Column --> ");
scanf("%d", &y);
do {
if (grid[x-1][y-1] == 1) {
grid[x-1][y-1] = 2; //We assign value 2 because we want to print only the ones the user hits, it will print X which means "hit and sunk".
sunk++;
printf("\nHit and sunk\n");
printf("Sunk ships:%d \n\n", sunk);
} else if (grid[x - 1][y - 1] == -1) { //It will print "*" which means "discovered water".
grid[x - 1][y - 1] = 0;
printf("\nMiss\n\n");
}
}while (sunk=!ships);
}
When using a function call in C, the value is passed by copy. This means that
int value = 0;
function(value);
printf("%d\n", value);
will always print the value 0, even if the function reads like
void function(int value) {
value++;
}
because within the function function, a copy of the int value is being incremented.
To fix this, pass a copy of the memory location of value, and then increment the number stored at that location.
int value = 0;
function(&value);
with
void function(int* value) {
(*value)++;
}
sunk is passed by value. It needs to be passed by reference. Send the pointer to sunk, and receive sunk as a pointer in the shoot function.
Alternatively, make sunk a global variable and increment it, although I'd not suggest this for bigger programs!
Read more about passing by value and passing by reference to prevent such things from happening in the future! :D