Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have trouble writing a recursive function in C:
void func(int n)
which for a given number n prints "1" and n zeroes after it.
for example:
func(3);
prints: 1000
func(5);
prints: 100000
No global variables (outside the function) are allowed and argument count must not be increased. No other helper functions allowed.
Just some pointers:
Why do you think you must print "1" only on the first call of the function?
Why can't you print it on the last call of the recursive function and then print all the 0's?
How will you determine if a call to the function is the last call in the recursive way? (Can the value of "n" hold the answer?)
I would suggest you look into static variables. you could set a static variable to tell if your function is being called recursively or not. If you're not allowed to use global variables, it's just a tricky work-around. And when your recursion is done, just set it back for the next call.
You can solve this problem using two functions, for example func and func_rec. func will print the 1 and it will once call the recursive function func_rec which will print only zeros (recursively).
#include <stdio.h>
void func(int k){
if(k==0){
printf("1");
return;
}
func(k-1);
printf("0");
}
int main(){
func(3);
return 0;
}
#include <stdio.h>
void func(int n)
{
static one = 1;
if (one == 1){
printf("1");
one--;
func(n - 1);
}
else {
if (n < 0){
printf("\n");
return;
}
else {
printf("0");
func(n - 1);
}
}
}
int main() {
func(5);
return 0;
}
The code is very trivial so, even it seems that its a homework, i'm giving out the code.
Your earlier question suggests that you are not so much into c coding. What i'm trying to do is to reduce your frustration by giving out the code, but with a twist.
Please answer us why the code i've given is not a "pure" function? why this solution should be discarded with ones which have global storage.
You should learn this stuff, its pretty interesting :)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Write a C-program that calls a function minus(). This function receives two arguments and returns the difference (regular subtraction, not absolute). This difference should be printed on screen.
My code is:
int minus(int a,int b)
{
int c = a - b;
return c;
}
int main()
{
int a = 4; int b = 5;
minus(a,b);
printf("%d", minus);
return 0;
}
I have two questions:
1.why a and b in
int minus(int a,int b)
are grey in Visual Studio? "int" is blue but a and b are grey.
2. I got this result but it should be -1.
Could someone help me please
a and b are grey because the editor is automatically coloring the code to help illustrate the program syntax. This may look funny at first, but, over time, your brain will become accustomed to it, and things that are the wrong colors will stand out. This will help you find mistakes in your program—when you make a mistake typing, something that should be a keyword will be colored like a parameter name, and you may notice it is the wrong color and take a closer look at what you typed.
In printf("%d", minus);, the minus is just the function. It is not the value returned by the function. To print the value returned by the function, use printf("%d", minus(a, b));.
You have undefined behavior here printing the function pointer using %d format specifier. (You have used the wrong format specifier that's why the Undefined behavior).
And the most probable way you would like is to printf("%d", minus(a,b));. You wanted to print the result of the subtraction not the function pointer itself.
You are missing an assignment
int minus(int a,int b)
{
int c = a - b;
return c;
}
int main()
{
int a = 4; int b = 5;
int d = minus(a,b);
printf("%d", d);
return 0;
}
you called the function minus() but you did not take the value returned by function in any variable so when you try to print minus then it will return the pointer value of function. so to get the correct answer hold the return value in variable and then print it int c = minus(a,b);
printf("%d", c); or you can call the minus function inside the print function like this printf("%d", minus()); as a beginner i will suggest you to implement the first suggestion it will increase the capacity to use statements in c.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
today i tried to do something new,but i didn't do that correct.Would anyone be able to do that and explain why is it so like that? Thank you in advance
#include<stdio.h>
void function(int a[],int n)/*The definition of function with void type,with parameters
int a[],int n */
{
int i;// declared count,type integer//
for(i=0;i<n;i++)//count goes from 0,to <n,and increment all time while goes//
printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//
printf("\n");// printing the newline //
}
main()
{
int a[]={1,2,3,4,5,6,7}; // declaration of array with 7 elements //
int n=5;// declaration of variable n type integer value of 5 //
function(a,n) // calling the function with parametres a,n//
} // end of sequence //
In my case i got the result of the 1,2,3,4,because i tought that the count goes from 1,to the one number less than n=5,but the IDE show the result of 135 ,i think the problem in my way is with counter...but all advices are welcome,thanks
Please make sure you are posting properly formatted valid C code.
Note that what you get is not one hundred and thirty five, but one, three, and five. You get that because you are incrementing the loop counter twice.
Here's a working, more readable version:
#include <stdio.h>
void function(int a[],int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
}
int main(void)
{
int a[]={1,2,3,4,5,6,7};
int n=5;
function(a,n);
return 0;
}
replace
printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//
with
printf("%d",a[i]);// printing on the screen integers (a[i],i=i+1)//
in your code you were incrementing i twice. Once in the while and once in the a[i++]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have written two similar programs for my programming class. I have shared the code for both programs due to them being similar in nature and both have compiler issues on the final line with return0; For the first string of code the error I receive is "expected a declaration" and "syntax error: 'return'". For the second code I receive the errors "return value type does not match the function type" and " 'display': 'void' function returning a value. I have deleted and added {} at different parts of both codes and tried to rearrange the code. Thanks for help in advance.
Code 1
#include "stdafx.h"
#define nums 7
void display(int *);
int main()
{
int channels[nums] = { 2,4,5,7,9,11,14 };
printf("Channels: ");
display(channels);
}
void display(int *channels)
{
int i;
for (i = 0; i < nums; i++);
{
printf("%d", *(channels + i));
}
}
return 0;
code 2
#include "stdafx.h"
#define nums 7
void display(int *);
int main()
{
int channels[nums] = { 2,4,5,7,9,11,13 };
printf("channels: ");
display(channels);
}
void display(int *channels)
{
int i;
for (i = 0; i < nums; i++)
{
printf("%d", *channels);
*channels++;
}
return 0;
}
Return value is always associated to functions. For example, if a function sums up 2 integers and returns the sum of the integers, it will look something like:
int sum( int a, int b ){
return a + b;
}
See here, the return type of the function is int, and what it returns is also an int, since addition of two integers gives you an integer. It's like 2 horses + 3 horses = 5 horses. You cannot do 2 horses + 3 lions = 5 mangoes. I hope you get the point of return value and type.
Now in code 1, the error is you put your return 0; statement out of the main() function. The program cannot detect which function is this return statement associated to. To correct this, move your return statement in the next line after you call the display() function, INSIDE main() function.
Similarly, in code 2, move the return statement from the display() function to the main() function, just as you did in the previous case. This is because void expects nothing to be returned, but you are returning an integer. This is the same like giving a millionaire a loaf of break when he says he doesn't need one, he will surely get frustrated!
Hope that helps.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.