#include <stdio.h>
int printArray(a[], unsigned int n){
if (n == 4){
printf("%d", a[4]);
}
else {
printf("%d", printArray(a,n+1)); // here is the error, I know. But why?
}
}
int main(){
int a[5] = {1,2,3,4,5};
printArray(a,0);
}
I am a begginer with C. I am trying to print each of the elements of the array, but it only prints the last one correctly, and not the former ones. I know there's something about recursive way wrong. It's the first time I use recursive way without return and using printf. Maybe is this that misleaded me?
Output:
$ ./a.out
5
0
1
1
0
You should print the array item, not the return value of the function, Use this code
int printArray(int *a, unsigned int n){
if (n == 4){
printf("%d", a[4]);
}
else {
printf("%d", a[n]);
printArray(a,n+1);
}
}
Related
I am a beginner to arrays in recursion so need some guidance.
I am trying to find whether an element is present in an array or not.
// Program to find whether an element exist in an array or not.
#include <stdio.h>
int arr[5]= {1,2,3,4,5};
int fooSearch(int array1[],int N,int i, int X)
{
if(i==N)
return 0;
else if (array1[i]==X)
return 1;
else
return fooSearch(array1,N,i++,X);
}
// N denotes total size 5
// i counter that moves from 0 to 4 and eliminate recursion when it reaches 5
// X is the element to be found
int main() {
fooSearch(arr,5,0,3);
return 0;
}
The error I obtained is Segmentation Fault (SIGSEGV).
Please guide me what wrong I am doing with this code.
i++ is a post-fix increment, which increments i after the expression containing it is evaluated. Thus, every call to fooSearch effectively becomes to fooSearch(array1, N, 0, X). Recursion is endless, hence the segfault (or a stack-overflow on my compiler). (You can confirm that i is unchanging by placing printf("%d\n", i) at the top of the function.)
Fix this by using pre-fix increments, which increment the variable before evaluation.
return fooSearch(array1, N, ++i, X);
Or use i+1, since you won't be reusing the local variable anyways.
return fooSearch(array1, N, i+1, X);
While calling fooSearch() recursively pass i+1 instead of i++ as post increment i++ doesn't change i in the argument. For e.g
fooSearch(array1,N,i+1,X);
to find whether an element is present in an array or not.
you can initialize number of array elements, Let's say 10 elements:
int num[10]= {2,3,5,6,1,8,4,9,0,7};
Then, Creating for loop for checking if number 9 is not in array then continue until the condition is false then print the element location.
for(i=0; i<10; i++){
if(num[i] != 9){
continue;
}
printf("9 is found here\n%d",i);
break;
}
At the end, You write an if condition to check if the loop is ended and print not found.
if(i==10){
printf("Not Found");
}
The full code is here:
#include <stdio.h>
int num[10]={2,3,5,6,1,8,4,9,0,7};
int i;
int main(void){
for(i=0; i<10; i++){
if(num[i] != 9){
continue;
}
printf("9 is found here\n%d",i);
break;
}
if(i==10){
printf("Not Found");
}
getchar();
return 0;
}
You have to use ++i or i+1 instead of i++.
i++ is a post increment operator, so the value of i that will go to the function will not change.
Just use ++i or i+1 and you will get the answer.
public static boolean checkNumber(int input[], int x) {
int n=input.length;
if(n==0)
return false;
if(input[0]==x)
{
return true;
}
int small[]=new int[n-1];
for(int i=1;i<n;i++)
{
small[i-1]=input[i];
}
return checkNumber(small, x);
}
// Program to find whether an element exist in an array or not.
// Number of elements of array is N, the number to search is X
#include <stdio.h>
int arr[]= {1,2,3,4,5};
int fooSearch(int array1[],int N,int i, int X)
{ if(i==N)
return 0;
else if (array1[i]==X)
return 1;
else
i=i+1;
return fooSearch(array1,N,i,X);
}
int main() {
int x = fooSearch(arr,5,0,9);
printf("%d",x);
return 0;
}
I am trying to make a program that converts a hex string into decimal. However I am having an issue assigning a returned integer value from the findLength function. Going by the printf statements I can tell that findLength(theString) will yield the correct value however length is showing a value of 0 despite the fact that I have length = findlength(theString).
This isn't a homework problem, I'm just absolutely stumped as to why this simple assignment isn't working. I've already declared length so I know that's not the issue. I'm also getting no compiler messages. Any help would be greatly appreciated.
Edit: I know convert doesn't do anything useful and the for loop needs to be fixed however that shouldn't be effecting the findLength return right?
Second Edit:
I've always submitted a string of '324' to be tested.
#include <stdio.h>
int convert(char s[], int theLength);
int findLength(char s[]);
int main(){
char theString[100];
int result;
int i;
int length;
printf("%s","Hello, please enter a string below. Press enter when finished.");
scanf("%s",theString); //Apparently scanf is bad but we'll learn better input methods later.
//For my tests I submitted a string of '324'.
length = (findLength(theString)); //length = findLength('324')
printf("%d",findLength(theString)); //yields 3
printf("%d",length); //yields value of 0 always.
result = convert(theString, length);
printf("%d\n result is",result);
return 0;
} //End of main
int convert(char s[], int theLength){ //This function will eventually converts a string of hex into ints. As of now it does nothing useful.
int i;
int sum;
for(i = theLength; i=0; i--){
sum = sum + s[i];
printf("%d\n",sum);
}
return sum;
} //End of convert
int findLength(char s[]){
int i;
for(i = 0; s[i]!='\0'; ++i){
}
return(i);
} //End of findLength
The variable length is storing the correct value. I think what has you confused is how you've laid out your printf statements. If you were to try something like the below it would be much easier to see that your code works.
#include <stdio.h>
int findLength(char s[]);
int main(){
char theString[100];
int result;
int i;
int length;
printf("Hello, please enter a string below. Press enter when finished.\n");
scanf("%s",theString);
length = (findLength(theString));
printf("findLength(theString) = %d\n",findLength(theString));
printf("length = %d\n",length);
return 0;
}
int findLength(char s[]){
int i;
for(i = 0; s[i]!='\0'; ++i){
}
return(i);
}
Just to clarify in your post you have
printf("%d",findLength(theString));
printf("%d",length);
printf("%d\n result is",result);
Note the \n before the %d in the last printf statement. This is 0 because your convert function needs to be fixed and this is the value of result NOT length.
I have been reading "The C Programming Language" and I got to this problem, that my output is 0 for any given string I send.
My function looks like this:
int number_of_repeating(char *word,char k){
int b=0,len=0,i;
gets(word);
len=strlen(word);
for(i=0;i<len;i++){
if(word[i]==k)
b++;
}
return b;
}
Problem:
I send him word for example: Jhonny, and character n, so it should count number of n's in the word (in this case the output should be 2).
What am I doing wrong?
#include <stdio.h>
int number_of_repeating(char *word,char k){
int b=0,len=0,i;
gets(word); //<------- You need to remove this one because it may overwrite
len=strlen(word);
for(i=0;i<len;i++){
if(word[i]==k)
b++;
}
return b;
}
int main(void) {
// your code goes here
printf("%d",number_of_repeating("johnny",'n'));
return 0;
}
if you're passing the string in there is no reason to call gets(), that could be it or your types could be wrong.
The Following two Codes Yield the same output but has some diffrence which i couldn't figure out
1.
#include<stdio.h>
int main(void)
{
int a=1;
while(a>0)
{
scanf("%d",&a);
if(a != 42)
printf("%d\n",a);
else
break;
}
}
2
#include <stdio.h>
int main(void) {
int x;
for(; scanf("%d",&x) > 0 && x != 42; printf("%d\n", x));
return 0;
}
The working is different because the semantics are different because the code is different.
If you would want to rewrite the 2nd part to the 1st, you would get
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d",&x) > 0 && x != 42) {
printf("%d\n", x);
}
return 0;
}
or
int main(void) {
int a;
while (scanf("%d",&a) > 0) {
if (x != 42) {
printf("%d\n", x);
} else {
break;
}
}
return 0;
}
Do you see the difference? On the one, you base your decision on the variable being scanned (x or a) and on the other on the return value of scanf(), which is simply the number of values read:
while(a>0)
vs.
while (scanf("%d",&a) > 0)
In the first case it's simple looping structure.
In the second case. The For Loop arguements like initialization of looping variable, condition and incrementation/decremenation are always options.
here For loop initialization is omitted, the condition scanf("%d",&x) will return no of values properly read from console, in case if you give any random character as input scanf return 0 and the condition x!= 42 is obvious. printf in the incremation/decrematation place just prints.
Only when the condition fails the loop terminates.
I have used the isPrime() function in other programs and it works perfectly, I have even referenced it in the same way before. For some reason in this program the function isn't working. I used printf() to check what the function was returning and it seems to be memory locations. I don't know what to change though because, as I said, I am sure the function works.
#include <stdio.h>
int main(void){
int isPrime(int a);
int result;
int x = 1;
while(x <= 1000){
result = isPrime(x);
if (result == 1){
printf("%d\n",x);
}
x++;
}
}
int isPrime(int a){
int count;
int z;
if(a == 1){
return 0;
} else {
for (z = a; z != 0; z-- ){
if(a % z == 0){
count++;
}
}
if(count <= 2){
return 1;
} else {
return 0;
}
}
}
Initialize count to 0.
Apart from this, on my system it works fine.
Move int isPrime(int a); out of the main() function, up above it. Or put it into a separate header file. Review function prototypes when you have time.
The count variable, in your program is a local variable, and hence like all local variables should be initialized before use or it uses a leftover value from the stack, and with such an unpredictable and random value , your program behavior is undefined.