Separate between numbers - c

I made this coding but I couldn't complete. The idea is should enter numbers and on the screen must shown as separately. Ex) If we enter:1234 result: 1 2 3 4.
#include<stdio.h>
int show_digit(int x);
int main(void)
{
int x;
printf("Enter the variable:");
scanf("%d", &x);
printf("%d ", show_digit(x));
return 0;
}
int show_digit(int x)
{
return show_digit(x / 10)%10;
}

You seemed to be trying to make show_digit() recursive, but you got stuck on how to actually do it. This refactored version of your function actually traverses from the last digit of the input to the first (which is the base case), and then starts printing out spaced digits as it comes out of the recursion. Note that I changed the return type of show_digits() to void because it is really now a utility function which does not compute anything.
void show_digit(int x)
{
if (x < 10)
{
printf("%d ", x);
return;
}
else
{
show_digit(x/10);
}
int the_digit = x % 10;
printf("%d ", the_digit);
return;
}

In this answer, I will not show you any code, but I will explain what's your issue.
I tried to compile your code, it compile successfully, but when I run it, the program crashed, is that your issue?
I know why your program crashed: Out of memory!
How did it happen?
Your function int show_digit(int) is a recursive function, in this function, you didn't made a statement to stop recursion, so, the recursion will continue until the function's stack reach maximum size of allowed memory, then it finally causes crashing.

Non-recursive version:
int digits[256];
int i = 0;
do {
digits[i++]=x%10;
x /= 10;
} while (x);
for (i=i-1; i>=0; i--) {
printf ("%d ", digits[i]);
}
It will work fine for positive integers.

Related

i have a problem with my code and i'm not sure if i even wrote it correctly

so i'm practicing c and i built a program that says if its prime number or not and i tried to execute it but it wont work it doesnt shows me the output oh and im still new to this i started learning c one week ago.
i dont know how to fix this.
#include <stdio.h>
void Num();
int main()
{
void Num();
return 0;
}
void Num()
{
int n, i, flag = 0;
printf("Enter a num: ");
scanf("%d", &n);
for(i = 1; i <= 10; i++)
{
for(n = 1; n <= 10; n++)
{
flag = 1;
}
}
if( flag == 1)
{
printf("its not the prime num ");
} else{
printf("its the prime num" );
}
}
it wont even show the printf output
You need to go back to the basics (this means: reading a good C book before diving in). You are confusing declaration and calling of functions.
int main()
{
void Num();
return 0;
}
main contains two statements:
A local (re)declaration of Num as a function without return value.
A return statement.
Since you want to call Num rather than redeclaring it, you need to use the function call syntax:
int main()
{
Num();
return 0;
}
This is just the first step, however. Your Num function does not perform the correct actions to determine primality.

Segmentation fault with recursive factorial implementation

Now I am practicing using Vim on Linux.
I made a simple code like this
#include <stdio.h>
int factorial(int n){
if (n<0) { return 0; }
else if (n==0) { return 1; }
else { return n * factorial(n); }
}
int main(void){
int n = 0;
printf("Put n value : ");
scanf("%d", &n); /* non-OP inserted ";" to help people focus on the problem */
printf("%d! = %d\n", n, factorial(n));
return 0;
}
When I put -1 and 0, it works. They return 0 and 1.
However, when I put positive integer values on n, it didn't work.
I tried to find out the reason so I used gdb,
but it just said like this :
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400620 in factorial ()
What's wrong with my code? I even cannot understand the point.
When n > 0 your recursive program never terminates. The value of n is never decremented and so it continues running recursively until your run out of memory.
It should be return n * factorial(n-1);
You code is causing stack overflow. In the given function n is never decremented. Last statement should be
else { return n * factorial(n-1); }

Creating a function for a random number 2D array

So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

Why does my PRIME1 - SPOJ implementation gets SIGSEGV, even though it runs fine for all test cases in my pc?

Input:
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Here's the link to the problem : http://www.spoj.com/problems/PRIME1/
Here is my program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int n,m,t,i=0,j,k=0;
int tm[10],tn[10];
scanf("%d",&t); //test cases
while(i<t)
{
scanf("%d %d", &tm[i],&tn[i]);
i++;
}
int * a = malloc((n+1)*sizeof(int));
while(k<t)
{
n=tn[k];
m=tm[k];
a[0]=a[1]=0;
for(i=2;i<=n;i++)
a[i]=i;
for(i=2;i<=sqrt(n);i++)
{
if(a[i])
{
for(j=(i*i);j<=n;j+=i)
{
a[j]=0;
}
}
}
for(i=m;i<=n;i++)
{
if(a[i])
printf("%d \n", a[i]);
}
k++;
printf("\n");
}
return 0;
}
Declaring an array of size 10^9 is not permitted on many coding sites.That might be causing SIGSEGV.
Any way you need to change logic of your code since even if you resolve this error , your logic will possibly give you TLE

Resources