I am working on CS50 and learning C. I am getting myself confused about utilizing while-do loops to ensure that the user puts in an integer. I am trying to create a function that prompts for your age and then your friend's age. However, after the first while-do loop returns false, shouldn't it move to the 2nd while-do loop in my get_ages() function? I would love some help on this.
#include <cs50.h>
#include <stdio.h>
int get_ages();
int main(void)
{
printf("%i\n", get_ages());
}
//Get your age function
int get_ages(int your_age, int friend_age)
{
do
{
your_age = get_int("What is your age: ");
return your_age;
}
while (your_age < 1);
do
{
friend_age = get_int("What is your friends age: ");
return friend_age;
}
while (friend_age < 1);
}
Your declaration int get_ages(); and your definition of the function int get_ages(int your_age, int friend_age) do not match. In main() you call get_ages() without arguments. If you want to pass data to caller via an argument (sometimes referred to as an out parameter) then you need to pass in the address of said variables:
int your_age;
int friend_age;
get_ages(&your_age, &friend_age);
The declaration would then be void get_ages(int *your_age, int &friend_age) you in the function you would set the value like this *your_age = get_int(...) etc.
return terminates a function and pass the optional value to caller. This means you will only ever execute a single return statement within a function.
In c, you can only return 1 value, so you need to return a struct or array if you have multiple things you want to return.
I suggest you change the function to just return a single value, pass in a prompt, then call the function twice:
#include <cs50.h>
#include <stdio.h>
int get_age(const char *prompt) {
int age;
do {
age = get_int(prompt);
} while (age < 1);
return age;
}
int main(void) {
printf("%i\n", get_age("What is your age? "));
printf("%i\n", get_age("What is your friend's age? "));
}
Related
I have an assignment where I have to print a users age and name based on their input.
Here is the code:
#include <stdio.h>
#include <string.h>
void GetUserInfo(int* userAge, char userName[]) {
printf("Enter your age: \n");
scanf("%d", userAge);
printf("Enter your name: \n");
scanf("%s", userName);
return;
}
int main(void) {
int userAge = 0;
char userName[30] = "";
//insert code here
printf("%s is %d years old.\n", userName, userAge);
return 0;
}
I can't change any code except for the //insert code here.
I'm pretty sure that I have to call the function but I can't figure out what parameters to pass the function. I tried
void GetUserInfo(int* userAge, char userName[]);
but as you can probably figure out it passes an empty string for a name and 0 as the age due to the initializations in the main().
The parameters you need for the function are a pointer to int and a pointer to char.
GetUserInfo(&userAge, userName);
The "&" operator gives you the address of the userAge variable that can be used as a pointer.
The compiler will take care of passing the start of the userName array of chars as second parameter.
I am new to C programming and I am trying to create functions. The first function executes but the second one doesn't.
#include <stdio.h>
char get_char();
int main(void)
{
char ch;
printf("Enter a character > ");
scanf("%c", &ch);
return ch;
}
int get_int()
{
int i;
printf("Enter an integer between 0 and 127 > ");
scanf("%d", &i);
return i;
}
For anyone else that arrives here, you may solve your problem, by making sure your main function is at the bottom of the file.
Why? Because if function a calls function b, a should be before b.
main is the entry point for your program. The C environment calls main when your program is executed. get_int() is not the name for an entry point, so the fact that you never call it directly or indirectly in main means it will never be executed.
You also didn't declare it before main meaning your compiler will warn about not finding it, but since get_int returns int it will link successfully regardless.
Fix:
int get_int();
int main ()
{
//...
}
int get_int()
{
//...
}
Your second function isn't called and it should be as follows:
int main()
{
int m = 10;
get_int(m);
return 0;
}
int get(int num)
{
int multiply = num * num;
return multiply;
}
I have learned how to use functions and structs and pointers. I want to combined them all into one. But the code that I write doesn't seem to work. The compiler tells me the test is an undeclared identifier. Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
void test (use_power)
int main ()
{
test (use_power)
printf("%d\n",*power);
return 0;
}
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
Your code has many mistakes it can't even compile
Multiple missing semicolons.
Implicit declaration of test() here
test (use_power)
with a missing semicolon too.
power is not declared in main().
This line
void test use_power()
does not make sense and is invalid, and also has no semicolon.
The a instance in test() defined at the end is local to test() and as such will be deallocated when test() returns. The use_power int, has exactly the same problem and trying to extract it's address from the function is useless because you can't access it after the function has returned.
I have no idea what you were trying to do, but this might be?
#include <stdio.h>
#include <stdlib.h>
struct character {
int *power;
};
/* Decalre the function here, before calling it
* or perhaps move the definition here
*/
void test(struct character *pointer);
/* ^ please */
int
main(void) /* int main() is not really a valid signature */
{
struct character instance;
test(&instance);
if (instance.power == NULL)
return -1;
printf("%d\n", *instance.power);
free(instance.power);
return 0;
}
void
test(struct character *pointer)
{
pointer->power = malloc(sizeof(*pointer->power));
if (pointer->power != NULL)
*pointer->power = 25;
}
Your code seems to be wrong. Your definition for test contains no arguments as
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
but your prototype contains one argument
void test (use_power)
which is wrongly put. First there are no semicolons; at the end of your prototype declaration, secondly by looking at your code, use_power is a variable and not a datatype so it cannot be present solely in a function declaration.
You will get an argument mismatch error.
You have used the line in main()
printf("%d\n",*power);
which is absolutely wrong. you cannot access any member of a structure without a structure variable.
And again, you have not mentioned the; after your call to the incorrect test()before this line
As you have not put your question so properly, I must figure out what you wish to achieve. I bet you want to hold the address of a integer in the pointer member of a structure and then print its value.
Below is a code snippet which will work as you desire.
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
struct character a; //define a structure variable
void test ();
int main ()
{
test ();
printf("%d\n",*(a.power)); // print the member of structure variable a
return 0;
}
void test ()
{
int use_power = 25;
a.power = &use_power;
}
example
#include <stdio.h>
struct character {
int *power;
};
void test(struct character *var);
int main (void){
struct character use_power;
int power = 5;
use_power.power = &power;
test(&use_power);
printf("%d\n", power);
return 0;
}
void test(struct character *var){
int use_power = *var->power;
*var->power = use_power * use_power;
}
Basically, why does it not just print the integers that are entered. Right now it just prints garbage value, but I do not know why it cannot access the values stored after it leaves the function. It only seems to get messed up after leaving the getIntegersFromUser function. If I run the for loop in the getIntegers function it does it properly, but why not in the main function?
Thanks in advance for your help.
#include <stdio.h>
#include <stdlib.h>
void getIntegersFromUser(int N, int *userAnswers)
{
int i;
userAnswers =(int *)malloc(N*sizeof(int));
if (userAnswers)
{ printf("Please enter %d integers\n", N);
for (i=0;i<N; i++)
scanf("%d", (userAnswers+i));
}
}
int main()
{
int i, M=5;
int *p;
getIntegersFromUser(M, p);
for (i=0;i<5;i++)
printf ("%d\n", p[i]);
return 0;
}
Also, this is a homework question, but it's a "Bonus Question", so I'm not trying to "cheat" I just want to make sure I understand all the course material, but if you could still try to give a fairly thorough explanation so that I can actually learn the stuff that would be awesome.
Pointers are passed by value. The function is using a copy of your pointer, which is discarded when the function ends. The caller never sees this copy.
To fix it, you could return the pointer.
int *getIntegersFromUser(int N)
{
int *userAnswers = malloc(...);
...
return userAnswers;
}
/* caller: */
int *p = getIntegersFromUser(M);
Or you could pass your pointer by reference so the function is acting on the same pointer, not a copy.
void getIntegersFromUser(int N, int **userAnswers)
{
*userAnswers = (int *) malloc(N*sizeof(int));
...
}
/* caller: */
int *p;
getIntegersFromUser(N, &p);
i have the following problems in C programming.
I have an array of strings stored as words[10][50]. I want to extract each of the string from the array and then pass it on to another function. I tried on the following:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char*,char*);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i][20]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i][20],words[i-1][20]);
}
getch();
}
int Check_Anagram(char *a,char *b)
{
printf("%s %s\n",a,b);
return 1;
}
This creates an exception during compiling.
Now i think that when i use the "printf" statement then this nomenclature works fine i.i words[i] prints the string "i" from the double dimension words array. When i try to do the same thing with the check function then the error occurs.
Can soemone point me how to do this passing ?
P.S. Please ignore any error in efficiency of program and likewise. I need your help and this is just a test program at learning string passing to a function
Thanks
You're passing words[i][20]. You need to pass words[i] instead in both loops. Try this:
for(i = 1; i < 3; i++) /* i < 3 */
{
flag = Check_Anagram(words[i], words[i-1]);
}
Another problem is that you're reading 3 strings and trying to print 10. So when you pass words[3] it contains garbage: printf tries to print garbage which need not be 0-terminated.
In the first for loop, when i is 0, you're pointing to words[-1], that's your exception.
flag = Check_Anagram(words[i][20],words[i-1][20]);
You are passing the 21st letter of each word the Check_Anagram. Instead you should pass the words themselves:
flag = Check_Anagram(words[i],words[i-1]);
You have a similar problem where you use scanf. To read a line from the console to each word you would use:
for(i=0;i<10;i++)
{
scanf("%s\n",words[i]);
}
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char [],char []);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i],words[i-1]);
}
getch();
}
int Check_Anagram(char a[],char b[])
{
printf("%s %s\n",a,b);
return 1;
}
I finally got it corrected thanks to the help of all users.
I have posted the corrected code for people who are struggling with passing of string extracted from an array of strings to another function. hope it helps.