why is the for loop going on infinitely in c - c

my question is when I run the code the loop goes on infinitely. the expected output is to print hi 5 times then go to a new line and print 4 times the 3 and so on I cant understand what is causing the loop to go infinite.
#include <stdio.h>
int star(int);
int main()
{
printf("enter number\n");
int a;
scanf("%d", &a);
star(a);
return 0;
}
int star(int m)
{
int n;
for (n = 0; n < m; n++)
{
printf("hi");
}
printf("\n");
star(m - 1);
return 0;
}

you forgot to check if m > 0 somewhere in your function. In this case, the loop goes infinetely, because it doesn´t have a way to get out of recursion.
Simple fix:
#include <stdio.h>
int star(int);
int main()
{
printf("enter number\n");
int a;
scanf("%d", &a);
star(a);
return 0;
}
int star(int m)
{
int n;
for (n = 0; n < m; n++)
{
printf("hi");
}
printf("\n");
if (m > 0){
star(m - 1);
}
return 0;
}

For starters the return type of the function star is useless and does not make a sense. Also there is no great sense to declare the parameter as having the signed integer type int. It would be more logically correct to declare the parameter as having at least the unsigned integer type unsigned int.
So the function should be declared like
void star( unsigned int n );
The function calls infinitely itself recursively because such a call is unconditional and does not depend on the value of the parameter m.
int star(int m)
{
//...
star(m - 1);
return 0;
}
The function can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void star( unsigned int );
int main( void )
{
printf( "Enter number: " );
unsigned int n;
if ( scanf( "%u", &n) == 1 ) star( n );
return 0;
}
void star( unsigned int n )
{
if ( n )
{
for ( unsigned int i = 0; i < n; i++)
{
printf( "hi" );
}
putchar( '\n' );
if ( --n ) star( n );
}
}
Pay attention to that if the function was called initially with the argument equal to 0 then the function should output nothing.

Related

summing numbers using pointer arithmetic

I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}

C code function calling not working

Ok I need to write two functions iterative and recursive to count negative elements in an array and then I need to build main. I was only able to write the recursive function but I cannot call it from main, it is an error somewhere. Can someone help me out solve it and help me with the iterative method?
#include <stdio.h>
main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(array, size)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
A working piece of code is this.You really need to take a look at pointers and the way they work.
Here you can see that I have a pointer ->pointing-< at the start of the array , so by passing the starting address of the array , and the length of the array , your functions knows what it is needed to be done.
#include <stdio.h>
int numero(int* array, int size);
int* recursive_count(int* array, int size , int* counter );
int main()
{
int vektor[100];
int* vekt_ptr = &vektor[0];
int i, madhesia;
int counter;
counter=0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
//int ret = numero(vekt_ptr, madhesia);
recursive_count(vekt_ptr, madhesia , &counter );
int ret = counter;
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array, int size)
{
int count = 0;
int j;
for (j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
int* recursive_count(int* array, int size , int* counter )
{
size--;
if(array[size] < 0 )
{
(*counter)++;
}
if(size==0)
{
return NULL;
}
return recursive_count(array++, size , counter );
}
Let's assume that you want to create dynamically an array of X length.
The compiler is going to have some memory for your array , depending on the length.
You initialize your array , lets say [2][45][1][-5][99]
When you call the function you have to pass where this is stored in memory.
int* vekt_ptr = &vektor[0]; -s going to give as something like 0x56c2e0.
This number is the address of your array , which is the address of the starting point of the array.This is equal with the address of first byte.
So when your function starts , it knows where your array starts and how long it is.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
Any function used in a program shall be declared before its usage.
This function declaration of the function definition
int numero(array, size)
{
// ...
}
is invalid because the types of the parameters array and size are undefined.
For the size of an array and for the count of elements it is better to use an unsigned integer type like for example size_t or at least unsigned int.
The program can look the following way
#include <stdio.h>
#define N 100
size_t iterative_numero( const int array[], size_t size );
size_t recursive_numero( const int array[], size_t size );
int main( void )
{
int vektor[N];
size_t madhesia = 0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%zu", &madhesia);
if ( N < madhesia ) madhesia = N;
/* Input array elements */
printf("Elementet: ");
for ( size_t i = 0; i < madhesia; i++ )
{
scanf( "%d", &vektor[i] );
}
size_t ret = iterative_numero(vektor, madhesia );
printf("\nTotal negative elements in array = %zu\n", ret);
ret = recursive_numero(vektor, madhesia );
printf("Total negative elements in array = %zu\n", ret);
return 0;
}
size_t iterative_numero( const int array[], size_t size )
{
size_t count = 0;
for ( size_t i = 0; i < size; i++)
{
if ( array[i] < 0 )
{
count++;
}
}
return count;
}
size_t recursive_numero( const int array[], size_t size )
{
return size == 0 ? 0 : ( array[0] < 0 ) + recursive_numero( array + 1, size - 1 );
}
the program output might look like
Madhesia e vektorit: 10
Elementet: 0 -1 2 -3 4 -5 6 -7 8 -9
Total negative elements in array = 5
Total negative elements in array = 5
First of all what you did is the iterative method, not recursive. Here I have called a recursive function from the main function.
#include <stdio.h>
int main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("\nElementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
printf("\nno of elements:%d",madhesia);
printf("\n");
for (i = 0; i < madhesia; i++)
{
printf("%d", vektor[i]);
}
printf("\n");
i=0;
int ret = numero(vektor,madhesia,0,i);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int array[],int size,int count,int j)
{
if (j<=size-1)
{
if(array[j]<0)
{
count++;
j++;
numero(array,size,count,j);
}
else
{
j++;
numero(array,size,count,j);
}
}
return count;
}
Put function prototype of numero() before main() to be able to call it. Declare function parameters with type:
int numero(int array[], int size);
int main() {
...
#include<stdio.h>
int numero(int *, int); //Function Prototype (1)
int main() //Return Type (2)
{
int vektor[100];
int i, madhesia;
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array,int size) //Parameters Data Type (3)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
Errors:
You have declared the function after "main()" so the program doesn't know that there is a function, so you have to give the function prototype before "main()" so that the program knows there is function ahead.
You missed writing the return type of "main()" which is integer.
In the function declaration you forgot to write the data type of the parameters.
NOTE: The array is always passed by reference so it has to taken in an integer pointer instead of a normal integer.
Some possible implementations:
int iterativeCountNegativeIntegers (int *array, int size)
{
int result = 0;
for (int i = 0; i < size; ++ i)
if (array[i] < 0)
result += 1;
return result;
}
int recursiveCountNegativeIntegers (int *array, int size)
{
if (size == 0)
return 0;
int partial = *array < 0;
return partial + recursiveCountNegativeIntegers(array+1, size-1);
}
The same, condensed:
int iterativeCountNegativeIntegers_1 (int *array, int size)
{
int result = 0;
while (--size >= 0)
result += *array++ < 0;
return result;
}
int recursiveCountNegativeIntegers_1 (int *array, int size)
{
return (size == 0) ? 0
: (*array < 0) + recursiveCountNegativeIntegers_1(array+1, size-1);
}

Factorial using pointers in C program

I want to create a program to find the factorial of a number also I want to make it using pointers.
I have tried to make a program but it is not giving the factorial of the number . Can anybody explains me why ?
#include<stdio.h>
#include<stdlib.h>
int fact(int* num, int* n)
{
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
}
int main()
{
int num, n;
printf("Write the number to take factorial \n");
scanf("%d", &num);
fact(&num, &n);
printf("Factorial = %d", n);
return 0;
}
As you are using int function it must contain some return value. If you make following changes it runs perfectly.
#include <stdio.h>
#include <stdlib.h>
int fact(int *num, int *n)
{
long long unsigned int fact = 1;
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
fact = fact * (*n);
}
return fact;
}
int main()
{
int num, n;
long long unsigned int b;
printf("Write the number to take factorial \n");
scanf("%d", &num);
b = fact( &num, &n);
printf("Factorial = %llu", b);
return 0;
}
*n=(*n)*(*num); is changing the value of the counting variable used in the for loop!
Whilst this is perfectly legal in C, it's leading to the incorrect answer.
You also don't return a value explicitly from fact despite it having a non-void return type. That's undefined behaviour.
Note also that the range for an int can be as small as -32767 to +32767, which only allows for 7! or lower. Consider using a long long type instead.
Correct me if I am wrong, but I think the logic itself is incorrect in your attempt :
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
You are using the counting variable ('*n' in this case) for purpose of storing the result. If you check the flow the loop will end after first iteration then increment it giving you the value of (*num + 1).
A good modification for your fact function could be :
void fact(int* num, int* n)
{
int counter;
*n=1;
for (counter = 2 ; counter <= (*num) ; counter++)
{
*n = (*n)*(counter);
}
}
Can't see a reason to keep the return type of the function as int if you are using call by reference for the result as well.
As in response to answer given by '#nikhil biijjala' , I can't understand your reason to pass the pointer (*n) in the first place.All that pointer does is works as a local counter for the loop.
As in case of large integers you can add limits to input or use long long.
C++ Version:
#include <iostream>
int abc(int *a);
int main()
{
int a,fact;
int *ptr;
std::cout << "Enter a:"<< std::endl;
std::cin >> a;
ptr= &a;
fact=*ptr;
while(*ptr!=1)
{
fact = fact * abc(ptr);
}
std::cout << "Factorial is : <<" << fact << std::endl;
return 0;
}
int abc(int *a)
{
*a=*a-1;
return *a;
}
#include<stdio.h>
int facto(int *);
int main()
{
int factorial, v;
printf("Enter the value : ");
scanf("%d", &v);
factorial = facto(&v);
printf("The factorial of %d is %d.\n", v, factorial);
}
int facto(int *p)
{
int c;
c = *p - 1;
if (*p == 1)
return 1;
else
return (*p) * (facto(&c));
}

I can not allocate memory in an array

#include<stdio.h>
#include<stdlib.h>
int crp(int mtrs[],int size)
{
int a=1;
int i;
for(i=0;i<size;++i)
{
a*=mtrs[i];
}
return a;
}
int main()
{
int k,size;
int **mtrs;
printf("enter the size of the matrix:");
scanf("%d",&size);
mtrs=(int**)malloc(size*sizeof(int*));
if( mtrs == NULL )
printf( "Yetersiz bellek!" );
printf("enter the input numbers of matrix:");
for(k=0;k<size;k++)
{
mtrs[k] =(int*) malloc( size* sizeof(int) );
if( mtrs[k] == NULL )
printf( "not enough memory!" );
}
for(k=0;k<size;k++)
{
scanf("%d",&mtrs[k]);
}
printf("\n\n");
for(k=0;k<size;k++){
printf("%d ",mtrs[k]);
}
printf("\n\n");
printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size));
return 0;
}
I get the problem of access violation reading location 0xFDFDFD.
it stucks at the location of a*=mtrs[i];.. The program's aim is to multiplication of the entered numbers
I am not sure if I am using the malloc in a correct way.
This code snippet is invalid
for(k=0;k<size;k++)
{
scanf("%d",&mtrs[k]);
&&&&&&&&
}
You should write for example
int m;
//...
for(k=0;k<size;k++)
{
for ( m = 0; m < size; m++ )
{
scanf("%d", &mtrs[k][m]);
}
}
The same is valid for this loop
for(k=0;k<size;k++){
printf("%d ",mtrs[k]);
}
It should look like
for(k=0;k<size;k++)
{
for ( m = 0; m < size; m++ )
{
printf("%d ",mtrs[k][m]);
}
printf( "\n" );
}
The function should be defined like
long long int crp( int * mtrs[],int size)
^^^^^^^^^^^^^ ^^^^^^^^^^^^
{
long long int a=1;
int i, j;
^^^^^^^^^
for(i=0;i<size;++i)
{
for ( j = 0; j < size; j++ )
{
a*=mtrs[i];
}
}
return a;
}
And the result of the function should be outputted like
printf("Elemanlar carpimi %lld dir.",crp(mtrs,size));
^^^^^
I do not fully understand what is your code point, but you have various mistakes and logic problems with it.
printf("%d ",mtrs[k]); and scanf("%d",&mtrs[k]); expect int but you passed *int (aka int[]), you probably need to insert/read values using 2 nested for loops.
printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size)); last cycle is for(k=0;k<size;k++), according to it k = size, so mtrs[k] is out of bounds, which cause application crash.

Factorial program c using recursive function in C with while loop

Factorial program using recursion in c with while loop.In this program once the execution reaches the function return statement it will not go back to the function call. Instead,it executes the function repeatedly. can anybody please tell me what's wrong in this program.
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}
The reason that your program gets into an infinite loop is that the loop
while (n > 1)
x = n * fact(n-1);
never decrements n. Since n never decreases, the program will never leave the loop. Peter is correct in the comments: change the while to an if, and you will have a factorial function that handles all positive parameters correctly. However, even after changing while to if, your fact won't have the property that fact(0) == 1, as is required for a correct factorial function.
This
while(n>1)
is causing the looping. You don't change n inside the loop, so the loop is infinite.
Change while to if.
This is the method of factorial:
public int fact(int n)
{
if (n < 1)
{
return 1;
}
else
{
return n * fact(n - 1);
}
}
#include <stdio.h>
#include <stdlib.h>
/** main returns int, use it! */
int main(int argc, char **argv)
{
if (argc <= 2) {
if (argv) argc = atoi(argv[1] );
else return argc;
}
argc *= main (argc-1, NULL);
if (argv) {
printf("=%d\n", argc);
return 0;
}
return argc;
}
/*
Write a C++ Program to input a positive number,
Calculate and display factorial of this number
by recursion.
*/
#include<iostream.h>
#include<conio.h>
long factorial(int n);
void main()
{
clrscr();
int number, counter;
label1:
cout<<"\n Enter the Number = ";
cin>>number;
if ( number < 0)
{
cout<<"\n Enter a non negative number, please!";
goto label1;
}
cout<<"\n\n ----------- Results ------------";
cout<<"\n\n The Factorial of the number "<<number<<"\n is "<<factorial(number);
getch();
}
long factorial(int n)
{
if ( n == 0 )
return 1;
else
return n * factorial(n-1);
}
You can use the simple approach using recursion
#include <stdio.h>
int fact(int n)
{
if(n==1)
return 1;
else
return n * fact(n-1);
}
int main()
{
int f;
f = fact(5);
printf("Factorial = %d",f);
return 0;
}
Read it more C program to find factorial using recursion
/*several versions of a factorial program.*/
#include<stdio.h>
int main()
{
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
factorial = 1L;
while(n > 0)
factorial *= n--;
printf("The factorial is %ld\n", factorial);
return 0;
}
#include<stdio.h>
/*the same, but counting up to n instead of down to 0*/
int main()
{
register int count;
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
factorial = 1L;
count = 1;
while(count <= n)
factorial *= count++;
printf("%d! = %ld\n", n, factorial);
return 0;
}
#include<stdio.h>
/*an equivalent loop using 'for' instead of 'while'*/
int main()
{
register int count;
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
for(factorial = 1L, count = 1; count <= n; count++)
factorial *= count;
printf("%d! = %ld\n", n, factorial);
return 0;
}
/*WAP to find factorial using recursion*/
#include<stdio.h>
#include<stdlib.h>
int fact1=1;
int fact(int no)
{
fact1=fact1*no;
no--;
if(no!=1)
{
fact(no);
}
return fact1;
}
int main()
{
int no,ans;``
system("clear");
printf("Enter a no. : ");
scanf("%d",&no);
ans=fact(no);
printf("Fact : %d",ans);
return 0;
}
Factorial program using recursion in C with while loop.
int fact(int n)
{
int x=1;
while(n>=1)
{
return(n*fact(n-1));
}
return(1);
}
You can use this approach.
int factorial(int a)
{
while(a>1)
{
return a*factorial(a-1);
}
return 1;
}

Resources