Skip to content

Commit

Permalink
Day 14 - C (#146)
Browse files Browse the repository at this point in the history
* Create sum_of_digits.c

* Create product_of_2_numbers.c

* Update README.md
  • Loading branch information
ashwek authored and MadhavBahl committed Jan 9, 2019
1 parent af75f9c commit 16cf02f
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 1 deletion.
37 changes: 37 additions & 0 deletions day14/C/product_of_2_numbers.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* @author: ashwek
* @date: 8/1/2019
*/

#include <stdio.h>

int product(int a, int b){

if( a == 0 || b == 0 )
return 0;
else if( a == 1 )
return b;
else if( b == 1 )
return a;

if( a < 0 && b < 0 )
return product(-a, -b);
else if( a < 0 )
return product(b, a);
else
return b + product(a-1, b);

}

void main(){

int a, b;

printf("Enter 1st number = ");
scanf("%d", &a);
printf("Enter 2nd number = ");
scanf("%d", &b);

printf("%d x %d = %d\n", a, b, product(a, b));

}
24 changes: 24 additions & 0 deletions day14/C/sum_of_digits.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* @author: ashwek
* @date: 8/1/2019
*/

#include <stdio.h>

int sum(int num) {
if( num <= 0 ){
return 0;
}
return (num%10) + sum(num/10);
}

void main(){

int num;

printf("Enter a number = ");
scanf("%d", &num);

printf("Sum of digits = %d\n", sum(num));

}
77 changes: 76 additions & 1 deletion day14/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,37 @@ public class SumDigits {
}
```

### C Implementation

#### [Solution](./C/sum_of_digits.c)

```c
/*
* @author: ashwek
* @date: 8/1/2019
*/

#include <stdio.h>

int sum(int num) {
if( num <= 0 ){
return 0;
}
return (num%10) + sum(num/10);
}

void main(){

int num;

printf("Enter a number = ");
scanf("%d", &num);

printf("Sum of digits = %d\n", sum(num));

}
```
<hr />
## Part B - Product of numbers
Expand Down Expand Up @@ -177,4 +208,48 @@ public class Product {
System.out.println("Product of numbers " + num1 + " and " + num2 + " is: " + recursiveProd(num1, num2));
}
}
```
```

### C Implementation

#### [Solution](./C/product_of_2_numbers.c)

```c
/*
* @author: ashwek
* @date: 8/1/2019
*/

#include <stdio.h>

int product(int a, int b){

if( a == 0 || b == 0 )
return 0;
else if( a == 1 )
return b;
else if( b == 1 )
return a;

if( a < 0 && b < 0 )
return product(-a, -b);
else if( a < 0 )
return product(b, a);
else
return b + product(a-1, b);

}

void main(){

int a, b;

printf("Enter 1st number = ");
scanf("%d", &a);
printf("Enter 2nd number = ");
scanf("%d", &b);

printf("%d x %d = %d\n", a, b, product(a, b));

}
```

0 comments on commit 16cf02f

Please sign in to comment.