How to create multiple functions in C - c

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

Related

Why is the 2nd while-do loop not running in my function

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? "));
}

Some problem in package function(Wrapper function )in C .How do i package a founction and let the callee founction return multipe values or structure

There are some problems thatconfuse me:
The callee function needs return a structure, but there is not a structure statment in caller function.
If i have to write the declaration in the calling function,it can not be called packaging function.
If i return a structure pointer by callee function, but the structure is in the stack of the called function and will be destroyed after the end, which is not safe. Sometimes i get some warning or even wrong!
I have a limited ideas but it not good. I put the structure into the heap by malloc and return the void*pointer. But this gave birth to a new problem :after each call to this function, in the caller, I cannot release the heap through the free() function,the complier can not identify variable name of structure pointer. I think it verey dangerous. I want when the callee function quit,it can be released by itself.
This is the first time I came to this website to ask questions and I just came into contact with c language,If there is something stupid please point it out.
I have to write the structure declaration outside. This program for judging prime number, and I want to package the founction "judging_number". I do not want to write the structure declaration when I want to call the founction "judging_number".
Please give me some help, I would be very grateful.
Sorry, this is my fault. I compiled it with clang++, I saved it as *.cpp, but I wrote c code in it.
What I mean is, can I put the declaration in the called function to realize the function modularization, how can I not declare a structure before calling the function? Is there any way I can not write a declaration. Like use founction in stdio.h.It is as convenient as using the functions of the standard library. Only need to write a line of function call and pass parameters, the called function can return multiple results.
#include <stdio.h>
struct boundary{
int L;
int R;
};boundary *range;
int *get_number()
{
int *nPtr = (int *)malloc(sizeof(int));
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", nPtr);
if (*nPtr == 1)
{
exit(1);
}
} while (*nPtr < 1);
printf("The object is %d\r\n", *nPtr);
return nPtr;
}
int judg_number(int N,boundary range){
if (N%range.L==0&&N!=2){
printf("The number %d is a composite number.\r\n", N);
}
else{
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
boundary* get_range(int N){
boundary *Ptr = (boundary *)malloc(sizeof(boundary));
*Ptr = {2,N-1};
printf("The range is between %d and %d .\r\n", Ptr->L, Ptr->R);
return Ptr;
}
int main(int argc,char**argv,char**env){
int*N;
while(1){
N=get_number();
range=get_range(*N);
judg_number(*N, *range);
free(N);
free(range);
}
getchar();
getchar();
return 0;
}
You dont need dynamic memory allocation here. If you want to retun an int, retun an int. If you want to retun a stuct return a struct.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
struct boundary {
int L;
int R;
};
struct boundary range;
int get_number()
{
int n;
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", &n);
if (n == 1)
{
exit(1);
}
} while (n < 1);
printf("The object is %d\r\n", n);
return n;
}
int judg_number(int N, struct boundary range) {
if (N % range.L == 0 && N != 2) {
printf("The number %d is a composite number.\r\n", N);
}
else {
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
struct boundary get_range(int N) {
struct boundary b = { 2, N - 1 };
printf("The range is between %d and %d .\r\n", b.L, b.R);
return b;
}
int main(int argc, char** argv, char** env) {
int N;
while (1) {
N = get_number();
range = get_range(N);
judg_number(N, range);
}
getchar();
getchar();
return 0;
}
BTW:
boundary get_range(int N) {... is invalid in C but valid in C++. In C it should be struct boundary get_range(int N) {...

How to write a function with argument as a char pointer to return the number of occurence of a certain character in a string

I tried to write a function with an argument as char type pointer to return the number of occurrence of a certain character ,say 'a', in a string.As it needs to be function,I assume main() couldn't be used here.I am using Dev-C++ IDE .
My code:
int countA(char *phrase)
{
int count=0;
for(;*phrase;++phrase)
{
if(*phrase=='a')
count++;
}
return count;
}
/*void main()
{
char a[20];
int i;
char *ptr;
gets(a);
ptr=a;
i=countA(ptr);
printf("i=%d",i);
getch();
}*/
It shows error i.e "undefined reference to `WinMain#16'" and"[Error] ld returned 1 exit status".
But when i uncomment the main() function ,the whole source code works fine.
You need some entry point function to link your executable - EntryPoint.
It's more safely to use standard C functions instead of your own, something like:
int countA(const char *phrase)
{
int count = 0;
if (!phrase)
return count;
while ((phrase = strchr(phrase, 'a'))) {
phrase++;
count++;
}
return count;
}

Why am I not able to access values that were stored in another function?

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

Expected expression error in C

I'm trying to create two functions. The first function accepts integer inputs from the user until they are between 0 and 100. The seconds function display the validation to the stdOut.
However, it keeps giving me an error saying "Expected expression" when I call the function.
#include <stdio.h>
// function prototype for the function input
int input(int);
// function prototype for the function validate
int validate(int);
//main function
int main(void)
{
//calling the function input
input(int x)
//calling the function validate
validate(int y)
return 0;
}
// Function definition for input
int input(int a)
{
int r;
printf("Enter the int value of r\n");
scanf("%d",&r);
}
// Function definition for validate
int validate(int b)
{
int r;
if(r>= 0 && r<= 100)
printf("Valid number");
else
printf("Invalid");
}
There is at least one bug on almost every line of this program.
This is a standard problem for which there is a whole lot of incorrect advice out there (most importantly, only the strtol/strtoul/strtod family of functions should be used to convert strings to numbers; never use the atoi family and never use scanf) so I am going to give a complete worked example of how to write this program correctly, including proper use of comments.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
long read_number_in_range(const char *prompt, long lo, long hi)
{
// a signed 64-bit number fits in 21 characters, +1 for '\n', +1 for NUL
char buf[23], *endp;
long rv;
for (;;) {
puts(prompt);
if (!fgets(buf, sizeof buf, stdin)) {
perror("stdin");
exit(1);
}
errno = 0;
rv = strtol(buf, &endp, 10);
if (endp != buf && (*endp == '\0' || *endp == '\n')
&& !errno && rv >= lo && rv <= hi) {
return rv;
}
// if we get here, fgets might not have read the whole line;
// drain any remainder
if (!strchr(buf, '\n')) {
int c;
do c = getchar();
while (c != EOF && c != '\n');
}
puts("?Redo from start");
}
}
int main(void)
{
long val = read_number_in_range("Enter the int value of r", 0, 100);
// do something with val here
return 0;
}
Read on for line-by-line nitpicking of the original program.
#include <stdio.h>
Correct.
// function prototype for the function input
Comment redundant with code.
int input(int);
Function signature incorrect (see comments on body of function).
// function prototype for the function validate
Comment redundant with code.
int validate(int);
Function signature incorrect (see comments on body of function).
//main function
Comment redundant with code.
int main(void)
{
Correct.
//calling the function input
Comment redundant with code.
input(int x)
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
//calling the function validate
Comment redundant with code.
validate(int y)
Value returned from input should be passed to validate, presumably, instead of a new uninitialized variable.
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
return 0;
}
Correct.
// Function definition for input
Comment redundant with code.
int input(int a)
{
Parameter a is unnecessary.
int r;
Correct.
printf("Enter the int value of r\n");
Minor: use puts when there is nothing to format.
scanf("%d",&r);
Never use scanf.
}
Missing return r;.
// Function definition for validate
Comment redundant with code.
int validate(int b)
{
Function has no return value, so should be void validate(int b).
int r;
Unnecessary variable.
if(r>= 0 && r<= 100)
r should be b on this line.
printf("Valid number");
else
printf("Invalid");
Minor: again, puts.
}
Correct.
You have some stray ints in your calls, they need to go.
The calls should probably be:
x = input();
validate(x);
You can't pass an integer to a function and expect it to change in the caller's context, that is not how C's pass-by-value semantics work. You should just return the number from input() instead, i.e. its prototype should be int input(void);.
You need to add semicolons at the end of each line of code in your main() function, and also remove the type specifier in the function calls. Also, don't forget to declare the variables x and y somewhere:
int main(void)
{
int x=0;
int y=0;
//calling the function input
input(x);
//calling the function validate
validate(y);
return 0;
}
I bet the compiler asks you for an expression in some place where you write a function declaration with a missing semicolon.
//calling the function input
input(int x)
//calling the function validate
validate(int y)
Neither of these is a function call.
#include <stdio.h>
int input(int*);
int validate(int);
int main(void){
int x;
input(&x);
if(validate(x))
printf("Valid number");
else
printf("Invalid");
return 0;
}
int input(int *r){
printf("Enter the int value of r\n");
scanf("%d", r);
return *r;
}
int validate(int r){
return r>= 0 && r<= 100;
}

Resources