While Loop to continually check user input for integer - c

I know this question has been asked before and I am sorry but I cannot find a solution for my code. I am a new student to the C language and my problem is that I am trying to create a while loop that continually asks the user to update the data if they enter non integers. I have looked into the isdigit() function and I think that would work. I just can't seem to make it work for my code, as in whenever I try creating a while loop with isdigit as its condition, I either get a infinite loop, or my isdigit returns values that I was not expecting. I think the problem could be that my scanf() is scanning three integers separated by '/' but I am not sure if that is where the problem is. Any help would be appreciated.
Here is the code in question
#include <stdio.h>
#include <ctype.h>
int calcAge(int a, int b, int c, int d, int e, int f);
int maxHeart(int a);
int heartRangeLow(int a);
int heartRangeHigh(int a);
int main(void) {
int birthMonth = 0, birthDay = 0, birthYear = 0, targetRangeLow = 0;
int month = 0, day = 0, year = 0, age = 0, heartRate = 0, targetRangeHigh = 0;
printf("What is your birthday?(written in MM/DD/YYYY)"
"\nHit Enter after you type it in.\n");
scanf_s("%d/%d/%d", &birthMonth, &birthDay, &birthYear);
printf("What is the date today?(written as MM/DD/YYYY)"
"\nHit Enter after you type it in.\n");
scanf_s("%d/%d/%d", &month, &day, &year);
age = calcAge(birthMonth, birthYear, birthDay, month, day, year);
heartRate = maxHeart(age);
targetRangeLow = heartRangeLow(heartRate);
targetRangeHigh = heartRangeHigh(heartRate);
printf("You are %d years old.\n", age);
printf("Your maximum heart rate is %d beats per minute.\n", heartRate);
printf("Your target-heart-range is %d"
" to %d beats per minute.\n", targetRangeLow, targetRangeHigh);
system("pause");
return 0;
}
int calcAge(int a, int b, int c, int d, int e, int f)
{
int age;
age = ((f * 10000 + d * 100 + e) - (b * 10000 + a * 100 + c)) * .0001;
return age;
}
int maxHeart(int a)
{
int heartRateMax;
heartRateMax = 220 - a;
return heartRateMax;
}
int heartRangeLow(int a)
{
int lowTarget = a * .5;
return lowTarget;
}
int heartRangeHigh(int a)
{
int highTarget = a * .85;
return highTarget;
}

to create a while loop that continually asks the user to update the data if they enter non integers.
Make a helper function.
Read user input with fgets() into a buffer and then parse it for valid input with strtol() or sscanf(), is...(), etc. Return 1, 0, EOF depending on input.
// Untested code
// 1 success
// 0 bad input
// EOF end of file
#define DATE_STR_SIZE 80
int enter_date_mdy(char *prompt, int *m, int *d, int *y) {
if (prompt) {
fputs(prompt, stdout);
fflush(stdout);
}
char buffer[DATE_STR_SIZE];
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
int n = 0;
sscanf(buffer, "%d /%d /%d %n", m, d, y, &n);
// If scan incomplete or extra junk at the end ....
if (n == 0 || buffer[n]) {
return 0;
}
// Additional tests as desired ....
if (*m < 1 || *m > 12 || *d < 1 || *d > 31) {
return 0;
}
return 1;
}
Sample use
int count;
do {
count = enter_date_mdy("What is your birthday?(written in MM/DD/YYYY)",
&birthMonth, &birthDay, &birthYear);
if (count == EOF) return(EXIT_FAILURE);
} while (count < 1);
do {
count = enter_date_mdy("What is the date today?(written as MM/DD/YYYY)",
&month, &day, &year);
if (count == EOF) return(EXIT_FAILURE);
} while (count < 1);
Tip: instead of "What is the date today?", research time(), mktime().

Related

How do I print ordinal indicators in a C program? Can't print numbers with 'st', 'nd', 'rd'. (Beginner)

#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.

Double usage of scanf() depends on call order

I wrote a program in C which takes as an input a value and an ordered Array of integers and performs a ternary search to find the value(if it exists) inside the Array.
I have seen all the possible problems with the usage of scanf and the related topics here in Stackoverflow.
I have noticed that there is a difference if I call the 2 scanf functions in reverse order.
If I use the code as it is below. First read the value and after the array from the user, the program and scanf functions as expected.
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
Although if I use the scanf inputs in the reverse order the second scanf never stops to get user input and read values left in the buffer.
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
I cannot understand what is the difference in the calling order.
I have tried the solutions mentioned in the other threads but none worked.
Just as a reference here is the whole code(working as expected):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int ternarySearch(int A[], int l, int r, int k){
int i;
int first,second;
if(l>r){
return -1;
}
i= (r - l)/3;
if(i==0){
i++;
}
first = i+l-1;
second = i*2+l-1;
if(A[first]==k){
return first;
}
else if(A[first]>k){
ternarySearch(A, l, first-1, k);
}
else
{
if(A[second]==k)
return second;
else
if(A[second]>k)
ternarySearch(A, first+1,second-1, k);
else
ternarySearch(A, second+1,r, k);
}
}
int main(){
const int maxarraylen = 1000;
int i;
int n;
int A[maxarraylen];
char string[250];
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
n=i-1;
//We assume the array is sorted otherwise we can use any sorting algorithm e.g. code from task1
scanf(" %d", &k);
int result;
result=ternarySearch(A, 0, n, k);
if(result==-1){
printf("The value was not found in the Array.\n");
}
else{
printf("The value was found in position no. %d.\n", result);
}
return 0;
}
Your problem is that you are not 'stepping over' your end input.
We can see this by doing an experiment using the following program:
#include <stdio.h>
#include <stdlib.h>
void main(void) {
FILE *f;
long f_pos;
int ret;
int i;
int data[5];
int data_last;
int search;
f = fopen("./input.txt", "r");
if (f == NULL) {
perror("fopen()");
return;
}
/* read in the values for the array */
data_last = -1;
for (i = 0; i < 5; i++) {
ret = fscanf(f, "%d", &(data[i]));
printf("fscanf(data[%d]): ret: %d\n", i, ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);
if (ret != 1) {
break;
}
data_last = i;
}
/* check that we read in at least one value */
if (data_last == -1) {
printf("no input data!\n");
return;
}
/* insert 'fix' here */
/* pre-load the 'search' with known garbage */
search = 987;
/* now read in the search value */
ret = fscanf(f, "%d", &search);
printf("fscanf(search): ret: %d\n", ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);
/* print out our info */
for (i = 0; i <= data_last; i++) {
printf("data[%d]: %d\n", i, data[i]);
}
printf("search for: %d\n", search);
return;
}
With the following data in input.txt:
123
456
end
456
The output is as follows:
fscanf(data[0]): ret: 1
ftell(): 3
fscanf(data[1]): ret: 1
ftell(): 7
fscanf(data[2]): ret: 0
ftell(): 8
fscanf(search): ret: 0
ftell(): 8
data[0]: 123
data[1]: 456
search for: 987
ftell() tells us where the file's cursor is, and in this case we can see that it is at byte 8... the e of the input line end.
It doesn't get past it, and thus the next attempt to read a number (%d) will fail too!
It's also a good idea to check the return values! We can see that the fscanf(&search) call has failed to read a number!
The solution is to insert this snippet just after we check that we recieved array values:
/* this is the 'fix' */
ret = fscanf(f, "end");
printf("fscanf(end): ret: %d\n", ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);

How to make compiler repeat until the number 0 is presed

I'm wondering how to make the compiler repeat itself if the user presses a random button at the end. But if the user presses "0" the compiler exits.
My code:
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <float.h>
struct mystruct
{
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
struct mystruct data;
float max = 0;
float min = FLT_MAX;
float sum = 0;
float avg = 0;
int i = 0;
float resultat = 0;
printf("Startnummer: \n");
scanf_s("%f", &data.startnummer);
printf("Hoppnummer:\n");
scanf_s("%f", &data.hoppnummer);
printf("Svarighetsgrad:\n");
scanf_s("%f", &data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("domarpoang %d\n", i + 1);
float f;
if (scanf_s("%f", &f) == 1)
{
if (f < min) min = f;
if (f > max) max = f;
data.domarpoangs[i] = f;
}
else
{
printf("error parsing float\n");
exit(0);
}
}
system("cls");
printf("Startnummer: %.1f \n", data.startnummer);
printf("Hoppnummer: %.1f\n", data.hoppnummer);
printf("Svarighetsgrad: %.1f\n", data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("Domarpoang %d: %.1f\n", (i + 1), data.domarpoangs[i]);
}
for (i = 0; i < 7; i++)
{
sum += data.domarpoangs[i];
}
sum = sum - (max + min);
avg = sum/5;
resultat = avg * 3 * data.svarighetsgrad;
printf("Hoppoang:%.2f \n", resultat);
printf("Tryck tangent for nytt hopp!");
getchar();
getchar();
return 0;
}
*If the user presses random button, the compiler repeat itself from the beginning
*If the user presses 0, the compiler exits.
Any help is appreciated, thank you.
This answer puts a loop around the body of your main() code, taking care to re-initialise some of the variables for the next iteration.
There are many SO questions about getting keyboard input and clearing the debris. I know of no simple standard ways of testing for keyboard input such as kbhit(), for taking a single key input such as getch() or for flushing the input. Even getchar() is horrible - it won't return until you have pressed "Enter" which it leaves in the input buffer. This has resulted in many SO answers with impenetrable (to me) formats for scanf() to flush the input, or testing if (getchar() == EOF) - which does not respond to the "Enter" key.
So I have put a simple wrapper around the main() code, which terminates when '0' is entered followed by a control char (because fgets() appends the newline) or terminator. This removes the need to clean up the input - except in the case where the user inputs some silly typing. GIGO!
#include <stdio.h>
#include <float.h>
#define BUFFSIZE 10
struct mystruct {
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
char kbuff [BUFFSIZE+1];
struct mystruct data;
float max;
float min;
float sum;
float avg;
int i;
float resultat;
do {
max = 0; // initialise for each loop
min = FLT_MAX;
sum = 0;
printf ("Body of your main loop\n");
fgets(kbuff, BUFFSIZE, stdin);
} while (kbuff[0] != '0' || kbuff[1] >= ' ');
return 0;
}

C scanf in loop continues automaticly without input

I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)
So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
scanf("%s", temp);
for(cj = 0; cj < k; cj++){
deeln[ci][cj] = temp[cj*2]-'0';
}
}
//loop while.
}
But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.
The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp = 0;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
//get input
scanf("%i", &k);
scanf("%i", &d);
char temp[20];
int deeln[d][k];
memset(deeln, 0 , sizeof(deeln));
memset(temp, 0 , sizeof(temp));
for(ci = 0; ci < d; ci++){
fgets(temp, 20, stdin);
for(cj = 0; cj < k; cj++){
ta = cj*2;
deeln[ci][cj] = temp[ta]-'0';
}
}
//loop while.
return 1;
}
Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!
Two places to look:
1)
cj = 0;//initialize cj before using here
scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier,
//and use an index operator - temp[?] (not sure I am using the right index)
2)
deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded)
An example of working code...
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
for(cj = 0; cj < k; cj++){
if(scanf("%i", &temp[cj]) != EOF)
{
deeln[ci][cj] = temp[cj]-'0';
}
else deeln[ci][cj] = -1;
}
}
getchar();
//loop while.
}
you can play with the index of temp[cj] to make it what you actually want, but I assume you are intending to read from stdin, then populate deeln[][] with that value, for each scanf.
If you want to parse a string containing spaces and digets, "1 3 8 5 3", you could use strtok()
But your code as it is is not reading a string in, it is reading integers.
This is not perfect, you will have to do some debug, but will illustrate strtok(). You have to enter spaces between each digit after indices are selected: i.e.:
3
3
4 6 8
2 4 7
1 2 8
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each
char *buf=0;
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
if(scanf("%s ", inStr[ci]) != EOF)
{
buf = strtok(inStr[ci], " ");
cj = 0;
while(buf && (cj < k))
{
deeln[ci][cj] = atoi(buf);
cj++;
}
}
}
//getchar();waits for user input, pauses execution
}

Find a two digit number with recursion

I'm trying to code something in C by using recursion.
The user writes two positive numbers of same length and the program gives him a new number, which is composed like this :
new number unity digit = the smallest digit in the second positive number that the user wrote.
new number ten digit = the biggest digit in the first positive number that the user wrote.
Very simple in fact, here is an example :
5642 and 2371
will give us : 61.
I tried something like this :
#include <stdio.h>
int calcPair(int a, int b){
int number = calcPair(a/10, b/10);
int digit1 = (number/10);
int digit2 = number%10;
if(digit1 < a%10){
digit1 = a%10;
}
if(digit2 > b%10){
digit2 = b%10;
}
return(number);
}
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
BUT the program doesn't run at all.. and closes.
Maybe someone can correct me ? Or helping me finding the mistake.
Thanks by advance.
Your recursion can never end. Consider the following line in calcPair:
int number = calcPair(a/10, b/10);
This statement will always be executed unless you make it conditional, such as:
int number;
if((a != 0) || (b != 0))
number = calcPair(a/10, b/10);
Eventually, because you're dividing both numbers by 10, this condition will prove FALSE.
Something like this:
int calcPair(int a, int b){
int number;
if (a < 10 && b < 10) {
number = a*10 + b;
} else {
int digita = a%10;
int digitb = b%10;
number = calcPair(a/10, b/10);
if(digita > number/10){
number = digita*10 + number%10;
}
if(digitb < number%10){
number = (number/10)*10 + digitb;
}
}
return number;
}
Also, a small fix to the main:
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
number = calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
I think you can refactor your code to be more expressive of your requirement, with a few helper functions.
int greater(int a, int b)
{
return (a>b);
}
int less(int a, int b)
{
return (a<b);
}
int pickDigit(int n, int (*func)(int, int))
{
int ret = n%10;
n /= 10;
while ( n > 0 )
{
if ( fun(n%10, ret) )
{
ret = n%10;
}
n /= 10;
}
return ret;
}
int getBiggestDigit(int n)
{
return pickDigit(n, greater);
}
int gteSmallestDigit(int n)
{
return pickDigit(n, less);
}
int numDigits(int n)
{
int ret = 0;
while (n > 0 )
{
++ret;
n /= 10;
}
return ret;
}
int calcPair(int a, int b)
{
if ( numDigits(a) != numDigits(b) )
{
// Deal with error.
}
return betBiggestDigit(a)*10+getSmallestDigit(b);
}
Whether or not you are allowed to (you did not specify in OP),
here is a recursive search method using strings :
Strings are just an array of char. because you are interested in distinguishing the individual digits within a larger integer, the char data type will be a sufficient size container to facilitate the comparison.
Using arrays of char (strings) within a recursive function with exit criteria of strlen() > 0 will allow you to walk through each integer, and select the appropriate value (min or max).
This approach uses two recursive functions: getMinDigit() and getMaxDigit(), both returning a char representing the maximum value digit, or minimum value digit of their respective original multi-digit integer. These results are then concatenated, and converted back into a two digit integer.
Here is the example code that given:
5642 and 2371
will give us : 61.
char getMinDigit(char *digit)
{
static char val='9';//largest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] < val) //test for smallest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMinDigit(digit);
}
else
{
digit[len-1] = 0;
getMinDigit(digit);
}
}
return val;
}
char getMaxDigit(char *digit)
{
static char val='0'; //smallest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] > val) //search for largest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMaxDigit(digit);
}
else
{
digit[len-1] = 0;
getMaxDigit(digit);
}
}
return val;
}
int calcPair(int a, int b)
{
char big[10]={""}, small[10]={""};
char Big, Small;
char result[3]={""};
sprintf(big, "%d", a);
sprintf(small, "%d", b);
Big = getMaxDigit(big); //recursive function
Small = getMinDigit(small); //recursive function
sprintf(result, "%c%c", Big, Small);
return atoi(result);
}
int main(void)
{
int result = calcPair(5642, 2371);
printf("%d", result);
return 0;
//for illustration, hard coded to OP values
//int a, b, number=0;
//printf("Please enter two positive number of same length:\n");
//scanf("%d", &a);
//scanf("%d", &b);
//calcPair(a, b);
//printf("The two-digit number composed from %d, %d is: %d", a, b, number);
//return 0;
}

Resources