How can I call with a int function in main function? - c

I have a requirement to insert something in the function main > my_isneg to call my_isneg function. How can I do it?
#include <unistd.h>
void my_putchar (char c)
{
write (1, &c, 1);
}
int my_isneg (int n)
{
if (n < 0) {
my_putchar (78); }
else {
my_putchar (80);
}
}
int main (void)
{
my_isneg();
}

It's somewhat unclear what you're asking, but maybe you want this:
...
// print 'N' 1 if the number n is strictly negative, print 'P' otherwise
int my_isneg(int n)
{
if (n < 0) {
my_putchar('N'); // use 'N' instead of 80 (it's more readable)
}
else {
my_putchar('P'); // use 'P' instead of 80
}
}
int main(void)
{
my_isneg(-1);
my_isneg(1);
my_isneg(2);
}
Output
NPP
Or maybe this, which matches the name my_isneg more closely:
...
// return 1 if the number n is strictly negative
int my_isneg(int n)
{
return n < 0;
}
int main(void)
{
if (my_isneg(-1))
my_putchar('N');
else
my_putchar('P');
if (my_isneg(1))
my_putchar('N');
else
my_putchar('P');
}
Output
NP

Related

Recursive print of binary number

I'm struggling to write a recursive way to print a binary number. Here is what I have so far:
int bin(unsigned char n)
{
if (n==0) {
return 0;
} else {
printf("%d", bin(n<<1));
}
}
bin(7)
What seems to be wrong with the logic above?
A few errors such as using << (shift up) instead of >> (shift down). Also not always returning something. I'm surprised the compiler didn't pull you up on that. You don't gain anything from a return value, So you may as well get rid of it.
A simple implementation could look like this. We need to have the wrapped function (bin_recur) to allow us to differentiate between 0 the input value and 0 which signifies its time to stop recursion.
#include <stdio.h>
void bin_recur(unsigned char n)
{
if (n > 0)
{
printf("%d", n & 1);
bin_recur(n >> 1);
}
}
void bin(unsigned char n)
{
if (n == 0)
{
printf("0\n");
} else
{
bin_recur(n);
printf("\n");
}
}
int main()
{
for(unsigned i = 0; i < 10; i++)
{
bin(i);
}
}
The fact that your bin function calls printf is not completely ideal. This is what's known as tight coupling and the function could be more reusable if it was not bound to how it is presented. Perhaps copying to a string is a good way or even using fprintf to print to a file.
Stopping when n is 0 is wrong.
This fails for the trivial case where n is 0 to start with.
What you really need to do is pass down a shift amount as a second argument and stop after 8 bits.
Using the return with value just gets in the way.
Here's some refactored code with a full diagnostic test:
#include <stdio.h>
void
bin2(unsigned char n,int shf)
{
if (shf <= 7) {
bin2(n,shf + 1);
printf("%d", (n >> shf) & 1);
}
}
void
bin(unsigned char n)
{
bin2(n,0);
}
int
main(void)
{
for (unsigned int chr = 0; chr <= 0xFF; ++chr) {
printf("%2.2X: ", chr);
bin((unsigned char) chr);
printf("\n");
}
return 0;
}
please add this lines to your code.
void binary(int n) {
if(n==0)
return;
binary(n/2);
printf("%d",n%2);
}
You need the print call to execute after the recursive function for this to work. Here's an example:
void bin(unsigned char n)
{
if (n > 1) bin(n>>1);
putchar(n&1 ? '1' : '0');
}
int main(void)
{
for (unsigned char i = 255; i; i--) {
printf("%d --> ", i), bin(i);
getchar(); // inspect element if you want
}
}
Link to running code here.

what thing i should change from this code

I want to make a program to count the sum of digits in a string but only using stdio.h
but the program needs to count until its less than 10
so the example you input 56 it would be 5+6=11 then 1+1=2 and so on
here's my code. For now I'm just confused how to check if its whether more than 9 or not
#include<stdio.h>
int plus(int n);
int main(void)
{
int n, digit, test;
scanf("%d", &n);
test = plus(n);
while(test != 0)
{
if(test > 9)
plus(test);
else
break;
}
printf("%d", test);
}
int plus(int n)
{
int digit=0,test=0;
while(n != 0)
{
digit = n%10;
test = test + digit;
n = n/10;
}
return test;
}
You are not storing the value returned by plus function in the while body.
You can change the condition in while to check whether it is greater than 9 or not, and assign test as test = plus(test);
So, your while will look like this.
while(test > 9)
{
test=plus(test);
}
You need to recursively call the function plus() until the value returned by it becomes less than 10. Like shown below:
int main(void)
{
int n=56;
while(n> 10)
{
n = plus(n);
}
printf("%d", n);
}

How to generate a new function in C?

I want a function that could take input a single integer from the user with validation, lets call it input_single_int. Such a function would greatly simplify my code. If a user gives incorrect input, then the function should show error and again prompt the user to fill out the correct input. The problem is the validation part, different inputs require different validation. Even if I send a validation function, how do I send the different parameters required by the validation function through input_single_int?
I want this function to be generic, so that I could use it multiple places. In the code given, if I add a parameter in input_single_int to accomodate input of variable b, I would have to change check_a function also, which I don't want to do. I also don't want to use global variables.
The only way which I could think of achieving this is through a function that could generate another function. Something like this:
func generate_check_b(int a) {
return int check_b(int b) { return (b > 0 && b < a); };
}
Is such a thing possible in C?
#define MM_SHOW 8
#define MM_QUIT 9
int input_single_int(int *var, char msg[], int exit_on_eq, int secondary_check(int val)) {
int inp_status, error, temp;
char skip;
do {
error = 0;
printf("%s", msg);
inp_status = scanf("%d", &temp);
if (inp_status != 1) {
error = 1;
do {
scanf("%c", &skip);
if (exit_on_eq) {
if (skip == 'e') {
system("clear");
return MM_SHOW;
} else if (skip == 'q') {
system("clear");
return MM_QUIT;
}
}
} while (skip != '\n');
}
if (!secondary_check(temp)) {
error = 1;
}
} while (error && printf("Please give a correct input.\n"));
*var = temp;
return 0;
}
int check_a(int a) { return a > 0;}
int check_b(int b, int a) { return (b > 0 && b < a);}
int main() {
int a, b;
char amsg[] = "a should be more than 0: ";
char bmsg[] = "b should be more than 0 and less than a: ";
input_single_int(&a, amsg, 1, check_a);
input_single_int(&b, bmsg, 1, check_b);
return 0;
}
A common idiom is a pair of parameters; a function and an opaque context pointer; so a simple case could be something like:
int check_range(int a, void *p) {
int *range = p;
return a >= range[0] && a < range[1];
}
struct Set { int n; int *vals; };
int check_set(int b, void *p) {
struct Set *s = p;
int i;
for (i = 0; i < s->n && s->vals[i] != b; i++) {}
return i < s->n;
}
If you look at the blocks extension to C supported by clang & gcc, it isn't far different from this, except that it is more sugary and has some really scary side effects.

Customized sort in the order mentioned {2,3....9,A,B,C,D,1,E,F,0}

I am currently implementing a logic to sort the alphanumerical numbers in the order as mentioned {2,3....9,A,B,C,D,1,E,F,0}. Is there a easy and a possible way to do this? I prefer only C programming.
The request is regarding the sort of the 1st nibble in the PI code of FM RDS stations. As Germany is the only country which supports 2 PI codes(D & 1), the order is maintained in this manner.
Thanks in advance guys.
You should write a function (e.g., int custom_compare(const void *p1, const void *p2); that defines this sorting order. That method will return 1 if p1 comes after p2, 0 if they are 'equal', and -1 if p1 comes before p2.
Then, write your sorting method and call your ordering function instead of comparing using operators. That is, instead of if (a < b), use if (custom_compare(&b, &a)).
Also, I created that function prototype above (specifically using pointers as the parameters) because it would work with the qsort library, which is a quicksort implementation that accepts a custom comparison function.
An Implementation
I decided to quickly do a implementation of what I suggested and a small test example.
#include <stdlib.h>
#include <stdio.h>
int custom_compare(const void *p1, const void *p2) {
char *param1 = (char*)p1;
char *param2 = (char*)p2;
int loc1 = 0;
int loc2 = 0;
char order[17] = "23456789ABCD1EF0";
int i;
for (i=0; i<17; i++) {
if (*param1 == order[i]) { loc1 = i; }
if (*param2 == order[i]) { loc2 = i; }
}
if (loc2 < loc1) {
return 1;
} else if (loc1 < loc2) {
return -1;
} else {
return 0;
}
}
void bubble_sort_string(char *string) {
if (!string || !string[0] || !string[1]) { return; }
int i;
int tail = 0;
char tmp;
while (string[tail]) { tail++; }
while (tail) {
i = 1;
while (i <= tail) {
if (custom_compare(&string[i-1], &string[i]) > 0) {
// swap
tmp = string[i];
string[i] = string[i-1];
string[i-1] = tmp;
}
i++;
}
tail--;
}
}
int main() {
char string[33] = "00FFEE11DDCCBBAA9988776655443322";
printf("old string: %s\n", string);
bubble_sort_string(string);
printf("new_string: %s\n", string);
return 0;
}
Output:
$ ./csort
old string: 00FFEE11DDCCBBAA9988776655443322
new_string: 2233445566778899AABBCCDD11EEFF00
$

C Programming. Comparing an array's contents.

I have an array as result of my program's input:
//1.
int i, numberOfOccurances;
for(i = 0; i < numOfOccurrances; i++) {
printf("%d",PrintOccurrances[i]);
}
and as an example output:
121
Now I want to compare this array so that I can print an additional statement, for example:
//2.
if (PrintOccurrances == 121) {
printf("This means blah");
} else if (PrintOccurrances == 232) {
printf("This means something else");
}
//what type of variable should i set and HOW should I set it at point 1?
//what type of string statement should I have at point 2.
Thanks for any assistance.
Make a comparison function and use compound literals at the call site:
#include <stdbool.h>
bool int_arr_cmp_n(int const * a, int const * b, size_t len)
{
while (len--)
if (*a++ != *b++)
return false;
return true;
}
Usage:
if (int_arr_cmp_n(PrintOccurrances, (int[]){1,2,1}, 3)) { /* ... */ }

Resources