How to work with functions and outputs C - c

I want to enter 4 numbers and display the largest possible number. Can anybody help me with this please? I have tried multiply different approaches, so do not wonder why there are so many libraries.
Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h> //pow
#include <limits.h> //char max
#include <ctype.h> //
int sort_alg(const void *a, const void *b)
{
char ab[32], ba[32];
sprintf(ab, "%d%d", *(int*)a, *(int*)b);
sprintf(ba, "%d%d", *(int*)b, *(int*)a);
return strcmp(ba, ab);
}
void max_numb(int *a, int len)
{
int i;
qsort(a, len, sizeof(int), sort_alg);
for (i = 0; i < len; i++)
printf("%d", a[i]);
putchar('\n');
}
int main(void)
{
int numbers[4];
for(int count = 0; count < 4; count++)
{
scanf("%d", &numbers[count]);
printf("%d", numbers);
}
max_numb(numbers, sizeof(numbers)/sizeof(numbers[0]));
return 0;
}

Why don't you try some algorithm. It's pretty easy to select just the maximum. You don't have to sort it
Try this:
int max(int a[],int len)
{
int max=a[0];
for(int i=0;i<len;i++)
{
if(max<a[i])
max=a[i];
}
return max;
}
Sorry if I misunderstood your query. I answered by the title.

If printing the largest of the numbers entered is your sole purpose, you can do it without any sorting algorithm. While getting inputs, just use a variable that stores the highest number entered till now, and update the variable if any new value greater than maxim is entered
Code
int main() {
int numbers[4];
int maxim = -99999; //any small that you can assue to be minimimum
for(int count = 0; count < 4; count++) {
scanf("%d", &numbers[count]);
printf("%d ", numbers[count]);
if(numbers[count] > maxim) {
maxim = numbers[count];
}
}
printf("\n") ;
printf("Maximum Value : %d\n", maxim) ;
return 0;
}
Sorry if I misunderstood your question.

the following proposed code:
performs the desired functionality.
cleanly compiles
documents why each header file is included
properly checks for errors from system functions
caveat: does not check that all entered numbers are positive ( >= 0 )
Notice that proposed code is failing to prompt the user for each value to input, so the user will be looking at a blank terminal, with a blinking cursor (and wondering what to do) So the code should be prompting the user for each number.
and now, the proposed code
#include <stdio.h> // scanf(), fprintf(), printf(), putchar(), sprintf()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // strcmp()
#define MAX_NUMBERS 4
// prototypes
int sort_alg(const void *a, const void *b);
void max_numb( int Numbers[] );
int main( void )
{
int numbers[ MAX_NUMBERS ];
for( int count = 0; count < MAX_NUMBERS; count++ )
{
if( 1 != scanf("%d", &numbers[count]) )
{
fprintf( stderr, "scanf for number: %d failed\n", count+1 );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
printf( " %d", numbers[ count ] ); // leading space for formatting
}
max_numb( numbers );
return 0;
}
int sort_alg(const void *a, const void *b)
{
char ab[32], ba[32];
sprintf(ab, "%d%d", *(int*)a, *(int*)b);
sprintf(ba, "%d%d", *(int*)b, *(int*)a);
return strcmp(ba, ab);
}
void max_numb( int Numbers[] )
{
qsort( Numbers, MAX_NUMBERS, sizeof(int), sort_alg);
putchar( '\n' ); // so output from 'max_numb()' will be on a new line
for (int i = 0; i < MAX_NUMBERS; i++)
printf( "%d", Numbers[i] );
putchar( '\n' );
}
a typical run of the proposed code outputs:
1 2 3 4
1 2 3 4
4321

Related

How to make this program considered as a recursive rfunciton

I have created the program that functionally works the way it is supposed to but I have to make it recursive and I was told that function void expand() is not considered as a recursive function. Any tips?
#include <stdio.h>
#include <string.h>
#define max_size 300
int main(){
char defstr[max_size]="The universe is ever expanding!";
int num, buff_num;
printf("Input how much to expand: ");
scanf("%d",&num);
buff_num=num;
expand(defstr, num, 0, 0);
return 0;
}
void expand(char str[max_size], int n, int dash, int i){
if(n>-1){
if(str[i+1]!='\0'){
printf("%c",str[i]);
for(int j=dash; j>0; j--)
printf("-");
expand(str, n, dash, i+1);
}
else if(str[i+1]=='\0'){
printf("%c", str[i]);
printf("\n");
expand(str, n-1, dash+1, 0);
}
}
}
The program is built to output this type of text depending on the user input of how many dashes.
T-h-e- -u-n-i-v-e-r-s-e- -i-s- -e-v-e-r- -e-x-p-a-n-d-i-n-g-!
T--h--e-- --u--n--i--v--e--r--s--e-- --i--s-- --e--v--e--r-- --e--x--p--a--n--d--i--n--g--!
T---h---e--- ---u---n---i---v---e---r---s---e--- ---i---s--- ---e---v---e---r--- ---e---x---p---a---n---d---i---n---g---!
It is a recursive function in that it calls itself. However, my guess is that is is supposed to print the entire string with dashes each time.
void expand(char *str, int num_dashes)
{
// End recursion
if (num_dashes < 0) return;
// Call recursively
expand(str, num_dashes - 1);
// Print entire string with dashes
for (int i = 0; str[i]; i++) {
if (i != 0) {
for (int j = 0; j < num_dashes; j++) {
fputc('-', stdout);
}
}
fputc(str[i], stdout);
}
puts("");
}

Check command line input in C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int allDigits(char *S) {
while ( *S ) {
if ( ! isdigit(*S)) return 0;
S++;
}
return 1;
}
int main (int argc, char *argv[]) {
int i, /*for loop index*/
sum=0; /*the sum of the arguments*/
for (i=1; i<argc; i++) {
if ( allDigits(argv[i]))
sum = sum + atoi(argv[i]);
else {
fprintf(stderr,"Usage: %s [<int> <int> ... <int>]\n",argv[0]);
exit(1);
}
}
printf("Sum of the %d integers is %d\n", argc-1, sum);
exit(0);
}
I got this example from my notes, which check the command line input to see whether is a number or not. However, there is one part I don't really understand how that works, in the function allDigits we used isdigit() to check the input. But why we put ! in front of isdigit?
Can anyone explain this part to me?

Optimize code to get following output in c

I had an interview last week. They asked me to write a code to print like this
input :5
0
101
21012
3210123
432101234
54321012345
i wrote the below code but he said i could optimize this more . i cant figure it out.
,
int main(){
int n,i,j,k,lim,num;
scanf("%d",&n);//getting input starting number of last row
lim=n;
int collen=n+2;//it denotes end of row
for(i=0;i<n+1;i++)
{
num=i;
k=0;
for(j=0;j<collen-1;j++){
if(j<lim)
printf(" ");
else if(num<0){
printf("%d",++k);
}
else{
printf("%d",num--);
}
}//j for
printf("\n");
collen++;
lim--;
}//i for
}// main end
I have different code at first attempt, I used flag to detect when num reaches for incrementing and decrementing, it was complex there was about 4 if inside second loop, so I optimized that code to the above one. He said can you optimize more? I have no idea to optimize it .
My question: can it be optimized? If it can be - please post the code
There are more for-loops than those comparing by <. for(i=0;i<n+1;i++) is much clearer written as for (i = 0; i <= n; i++).
If you initialize a value, in example int collen=n+2;, and later use it like collen-1, save the subtraction and initialize it adjusted.
Separate this complex inner loop with ifs into their own loops.
Use less variables.
Use more and consistent whitespace.
And now my solution, but as yours it can only handle inputs from 0 to 9:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("input :");
if (scanf("%d", &n) != 1 || n < 0 || n > 9) {
printf("input not recognized or invalid\n");
return EXIT_FAILURE;
}
for (int i = 0; i <= n; ++i) {
printf("%*d", n - i + 1, i);
for (int j = i - 1; j >= 0; --j) {
printf("%d", j);
}
for (int j = 1; j <= i; ++j) {
printf("%d", j);
}
printf("\n");
}
return EXIT_SUCCESS;
}
This looks optimized to the brims:
int main( int argc, char **argv )
{
puts( "input :5");
puts( " 0");
puts( " 101");
puts( " 21012");
puts( " 3210123");
puts( " 432101234");
puts( "54321012345");
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Print a pyramid */
int
main(int argc, char **argv)
{
int size = argc > 1 ? strtol(argv[1],NULL,10) : 5;
if( size > 9 || size < 0) {
fprintf(stderr, "Invalid size\n");
return EXIT_FAILURE;
}
for(int line = 0; line <= size; line++) {
char template[]="9876543210123456789";
char *s = template + 9 - size;
template[10 + line] = '\0';
memset(s, ' ', size - line);
if(puts(s) == EOF) {
perror("puts");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}

Can I put a for loop inside scanf?

I want to have unknown amount of inputs in a single line. For example, user can input:
"ans: 1 2 3 4 5"
and scanf() will store these five numbers to an array. The problem is that the program don't know how many input will there be.
#include <stdio.h>
int main()
{
int i;
int input[4];
scanf("ans: " for(i = 0, i < 3,i++){scanf(" %d", &input[i]);};
return 0;
}
Sorry I'am totally new to coding, what will be the proper way to write this? Or is this impossible?
Thanks :)
Use fgets() and sscanf() with "%n"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char input[100];
int arr[10];
//fgets(input, sizeof input, stdin);
strcpy(input, "1 2 42 56 -3 0 2018\n"); // fgets
char *pi = input;
int tmp, pp, i = 0;
while (sscanf(pi, "%d%n", &tmp, &pp) == 1) {
if (i == 10) { fprintf(stderr, "array too small\n"); exit(EXIT_FAILURE); }
pi += pp;
arr[i++] = tmp;
}
printf("got this ==>");
for (int k = 0; k < i; k++) printf(" %d", arr[k]);
puts("");
}
You asked this question way round.
You can achieve what you expect by putting scanf inside of a loop.Even you can ask user to give how many inputs he want to enter.
#include <stdio.h>
int main()
{
int i;
int input[4];
printf("Enter the number of inputs you want to give : ");
scanf("%d", &n);
for(i = 0; i < n;i++)
{
printf("Enter the input number %d : ",i);
scanf("%d", &input[i]);
}
return 0;
}

How to replace a character at random in a string?

I've printed a string of "+" symbols based on two given values(N, M). Now I'm trying to figure out how to replace characters at random in said string based on a third given value(K). The characters are stored in a string(l). I think I have to use the replace function but I don't know how(hence why it's in a comment for now). Any help is appreciated.
#include <stdio.h>
unsigned int randaux()
{
static long seed=1;
return(((seed = seed * 214013L + 2531011L) >> 16) & 0x7fff);
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char s[1000];
int N, M, K, l;
printf("N: ");
scanf("%d",&N);
printf("M: ");
scanf("%d",&M);
printf("K: ");
scanf("%d",&K);
printf("\n");
gets(s);
l=strlen(s);
/* Mostre um tabuleiro de N linhas e M colunas */
if(N*M<K){
printf("Not enough room.");
}else if(N>40){
printf("Min size 1, max size 40.");
}else if(M>40){
printf("Min size 1, max size 40.");
}else{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
printf("+", s[j]);
}
printf("\n", s[i]);
}
for(int l=0; l<K; l++)
{
/*s.replace();*/
}
}
return 0;
}
There is too much unexplained complexity and unknowns in your program to enable a corrective answer. But this shows how to replace a textual string's character at random, with a numeral.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
char str[] = "----------";
int len = strlen(str);
int index;
int num;
srand((unsigned)time(NULL)); // randomise once only in the program
printf("%s\n", str); // original string
index = rand() % len; // get random index to replace, in length range
num = '0' + rand() % 10; // get random number, in decimal digit range
str[index] = num; // overwrite string character
printf("%s\n", str); // altered string
return 0;
}
Program sessions:
----------
-3--------
----------
-----0----
----------
--------6-
Arguably it would be better to use size_t types, but for the limited range of the example, will suffice.

Resources