I am trying a write a program that prints a pyramid by calling a function (pass by value and not pass by address).
Well, the function is just supposed to run a for loop to print the pyramid but the actual printing statement is written in the main. The rest of the program seems fine but there is an error in the function call.
Can you please tell me what I am doing wrong? It is the syntax that I am having trouble with. The error is "argument of type void is incompatible with parameter type of 'constant char*'"
#include<stdio.h>
void pyramid(int); //function declaration
int main()
{
int r1;
printf("Enter the number of rows you would like printed:");
scanf("%d",&r1);
printf(pyramid(r1)); //function call
return 0;
}
void pyramid(int r2) //function definition
{
int i,j;
for(i=r2;i>=1;i--)
{
for(j=r2;j<=i;j--)
{
printf("*");
}
printf("\n");
}
}
void pyramid(int); //function declaration
Here the function pyramid will not return any value,
But you are expecting it to return a value in the below statement
printf(pyramid(r1)); //function call
Also this program would run in to an infinite loop,
Here:
for(i=r2;i>=1;i--)
{
for(j=r2;j<=i;j--) //**j will always be less than i**
{
printf("*");
}
printf("\n");
}
printf's prototype is
int printf(const char *restrict format, ...);
But you are trying to pass void to it by calling printf(pyramid(r1));. Call function directly like pyramid(r1); instead of printf(pyramid(r1));.
Related
a. In the first function print “Hello, I’m in function 1”. Call the second function.
b. In the second function ask the user to enter a float value. Call a third function and pass the value to it.
c. In the third function calculate the square root of the number. Return the square root to the second function, then the first function and then to main.
d. Print the square root in main in TWO decimal places.
Please correct my coding for since I'm not getting the desired output.
float a(float);
void b(float);
void c(float);
void main(float d)
{
printf("In main\n");
printf("back in main \n");
printf("The square root is %f", d);
}
float a(float c)
{
printf("Hello,I'm in function 1");
return (c);
}
void b(float b)
{
float number;
printf("in function 2");
printf("enter a float value");
scanf("%f", &number);
c(number);
return a(number);
}
void c(float a)
{
float power;
printf("in function 3");
power = sqrt(a);
return b(power);
}
What libraries have you included? stdio.h is required for printf function and math.h is also required to implement the sqrt() function.
#include <stdio.h>
#include <math.h>
Your functions are incorrectly defined:
a requires no input and returns no data so it should be void
b returns float variable so it should be labelled as such.
c has type float for input as well as output
void a(void);
float b(void);
float c(float);
printf is not the way to call your functions.
You simply type the name of the function and arguments if you have any into your main function in the order you wish to call them.
example:
void main()
{
//declare your variable
float num;
//calls a function
a();
//calls b function and initializes num as value returned from b
num = b();
//calls c function and passes variable num to parameter in c function
c(num);
}
This should get you headed in the right direction.
In an interview I was asked to write an efficient program such that for each integer value given, a function is called.
For example: if user enters 1 then function one will get executed if user enters 5 then function five gets executed and so on..
I was not able to come up with an efficient idea, like we can't use an if statement for checking the value entered and then executing the corresponding functions.
Is there any way we can do this in an efficient manner?
One of the option would be using function pointers, as below.
Declares a type of a void function
typedef void (*fp)();
define your functions
void func1()
{}
.
.
.
void func10()
{}
declare array of function pointers like below
fp function_pointers[10]; //declares the array
Initialize the function pointers like below
function_pointers[0] = func1()
.
.
function_pointers[9] = func10()
Call function using function pointers like below
for (int i=0;i<10;i++)
function_pointers[i]();
Use function pointers.
Simple example:
#include <stdio.h>
//pointer to a void function declaration
typedef void(*someFunc)();
void f1() {
printf("f1 function call\n");
}
void f2() {
printf("f2 function call\n");
}
void f3() {
printf("f3 function call\n");
}
//array of function pointers
const someFunc funcTable[] = {
f1,
f2,
f3
};
int main() {
uint number = 0;
printf("Enter 0, 1 or 2\n");
scanf("%u",&number);
if(number < 3) {
funcTable[number]();
}
}
How do pass an array of pointers to functions as a argument to a function? If the types of the functions are void and so is the pointer, how do you access the functions?
int main() {
void(*fun_ptr[])(void) = {fun1, fun2, fun3};
pickFun(fun_ptr);
return 0;
}
All 3 functions only print a message and are declared as void
void pickFun(void *function_ptr[])
{
int pick = 0;
while(pick != 0)
{
scanf("%i", &pick);
*(function_ptr + (pick - 1));
}
}
I can never get the function's printf statements to appear when a function is chosen. The program just loops and never prints the message contained in each function. Any suggestions or clues?
Function parameter void *function_ptr[] is of type pointer to pointer tovoid`. You need to change it to
void pickFun(void (*function_ptr[])(void));
Also note that, as others pointed out in comments, program never enters the loop body. Better to use do while loop here
void pickFun(void *function_ptr[])
{
do
{
scanf("%i", &pick);
//*(function_ptr + (pick - 1));
function_ptr[pick-1](); //Function call. pick should not be greater than 3
} while(pick != 0)
}
Also, you can call your functions with:
(*function_ptr[pick-1])();
or (yuck):
(*(function_ptr + (pick-1)))();
or:
function_ptr[pick-1]();
or:
(function_ptr + (pick-1))();
I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.
Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.
You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error
I am learning C and I am studying functions. So, I read that when I implement my own function I have to declare it before the main(). If I miss the declaration the compiler will get an error message.
As I was studying this example (finds if the number is a prime number),
#include <stdio.h>
void prime(); // Function prototype(declaration)
int main()
{
int num, i, flag;
num = input(); // No argument is passed to input()
for(i=2,flag=i; i<=num/2; ++i,flag=i)
{
flag = i;
if(num%i==0)
{
printf("%d is not prime\n", num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime\n", num);
return 0;
}
int input() /* Integer value is returned from input() to calling function */
{
int n;
printf("\nEnter positive enter to check: ");
scanf("%d", &n);
return n;
}
I noticed that a function prime() is declared, but in the main, a function, input(), is called and also the function input() is implemented at the bottom. Ok, I thought it was a mistake and I change the name from prime to input.
However if I delete the declaration and I don’t put any there, the program is compiled without errors and it runs smoothly. (I compile and run it on Ubuntu.)
Is it necessary to declare a void function with not arguments?
If you don't have a forward declaration of your function before the place of usage, the compiler will create implicit declaration for you - with the signature int input(). It will take the name of the function you called, it will assume that the function is returning int, and it can accept any arguments (as Bartek noted in the comment).
For this function, the implicit declaration matches the real declaration, so you don't have problems. However, you should always be careful about this, and you should always prefer forward declarations instead of implicit ones (no matter if they are same or not). So, instead of just having forward declaration of the void prime() function (assuming that you will use it somewhere), you should also have a forward declaration of int input().
To see how can you pass any number of the arguments, consider this:
#include <stdio.h>
// Takes any number of the arguments
int foo();
// Doesn't takes any arguments
int bar(void)
{
printf("Hello from bar()!\n");
return 0;
}
int main()
{
// Both works
// However, this will print junk as you're not pushing
// Any arguments on the stack - but the compiler will assume you are
foo();
// This will print 1, 2, 3
foo(1, 2, 3);
// Works
bar();
// Doesn't work
// bar(1, 2, 3);
return 0;
}
// Definition
int foo(int i, int j, int k)
{
printf("%d %d %d\n", i, j, k);
return 0;
}
So, inside the definition of the function you're describing function arguments. However, declaration of the function is telling the compiler not to do any checks on the parameters.
Not declaring a prototype and relying on default argument/return type promotion is dangerous and was a part of old C. In C99 and onward it is illegal to call a function without first providing a declaration or definition of the function.
my question is, is it necessary to declare a void function with not arguments?
Yes. For this you have to put void in the function parenthesis.
void foo(void);
Declaring a function like
void foo();
means that it can take any number of arguments.
If prime is not used, then omit the declaration.
The code won't compile as C++, because the compiler would complain that function input is used but not declared. A C compiler might issue a warning, but C is more relaxed and does an implicit declaration of input as int input() which means that you can pass any value to input and input returns an int.
It is good style to always provide a function declaration before using the function. Only if you do this the compiler can see if you are passing too few, too many or wrongly typed arguments and how to correctly handle the return value (which might be short or char instead of int).