changing int main to void

323 Views Asked by At

I have written a working program but the form is incorrect for the task. Can somebody please help me change the code to

"void lower(char* s)"

Tried to change and position it but no working outcome. Doesnt fully understand the void type and one function in other and so on.

Code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main ()
{
  int i=0;
  const char s[]="SoMeThing SOmEThing stRing\n";
  char lower;
  printf("%s",s);
  while (s[i])
  {
    lower=s[i];
    putchar(tolower(lower));
    i++;
  }
  return 0;
}

Thank you

3

There are 3 best solutions below

2
On

I am not sure this is what you are looking for, but it might be.

From your title and the highlighted portion, I am assuming that you want to get rid of

int main() {}

and title it

void lower(char *s) {}

While you can easily do that with a copy paste, understand that this file can not be compiled on its own anymore. The C compiler will look for a

[return type] main() {}

to be the starting point for the program. With out this, there is no program.

I believe you are wanting to make a library and use the lower function in another program. To do this, I would create a .h file with the includes and function name:

void lower(char *s);

This can replace all of your other includes with a single include of this file:

#include "file.h"

You can use the above line in other programs to make this function available in these programs. If you have multiple functions in a library file and you do not want them all to be accessible outside of the file, ensure you use the 'static' keyword in front of methods you do not want available:

static int otherFunction();

Let us know if this is what you are looking for answer wise. If not, please try to clarify your request.

0
On

This function should work.

#include <string.h>

/* The function changes every upper-case letter of string s
   to its corrispondent lower-case. */
void lower(char *s)
{
    /* Iterates through string */
    for (int i = 0; i != strlen(s); i++) {
        s[i] = tolower(s[i]);
    }
}

The void type means that the function doesn't return any value: it just does some work and terminates, but it doesn't return anything to the caller.

Note that this function will change the characters of the string s instead of just printing them.

2
On
#include <stdio.h>
#include <ctype.h>

void lower(char *s){
    for(;*s;++s)
        *s=tolower(*s);
}

int main (){
    char s[]="SoMeThing SOmEThing stRing\n";

    printf("%s",s);
    lower(s);
    printf("%s",s);

    return 0;
}