Home > Back-end >  I need serious guidance for an assignment. (NOT ASKING FOR ANSWERS) Questions are at the bottom
I need serious guidance for an assignment. (NOT ASKING FOR ANSWERS) Questions are at the bottom

Time:11-12

To preface: THIS ASSIGNMENT IS DUE IN LESS THAN 7 HOURS. I've been attempting this assignment literally every single day for the last week. Today I spent 8 hours on it alone. I'm so behind in this class, if I don't pass this assignment and every assignment after this, I will fail. I really don't want to fail.

Some code from yesterday: I'm trying to make a function to take user input of a palindrome. Why is it after I take input for one array, it automatically inputs the rest?

(ALSO: The best way for me to learn is to be asked questions. If you guys ask me questions I'll answer them to the best of my ability, and if I'm wrong correct me.)

Here's the assignment:

Restrictions:

  1. You can use 1 or 2-Dimensional arrays for this exercise.
  2. DO NOT use pointers, they are not allowed for this exercise.
  3. DO NOT use global variables.
  4. DO NOT use library functions other than printf, scanf, fgets and strlen. The aim is to build as much of the functionality yourself.

Criteria:

  • You will choose the number of strings that the user will enter (a minimum of 5 is required). A string can be 1 or more words enclosed by double quotes.
  • You should use a #define COUNT <constant> to set the number of strings that will be entered. constant can be any number greater than or equal to 5.
  • You will create a minimum of 3 functions. You are allowed to create extra functions if warranted.
  • You MUST place those 3 functions after the declaration of main.
  • You MUST create header file(s) and place all constants and prototypes in the .h file(s).

Functions:

  1. The 1st function called getStrings will accept COUNT strings from the user
  • Each string entered should be a maximum of 30 characters.
  • The function should return the length of the longest string the user entered.
  • You may use a static variable if you call getStrings multiple times. This is the easiest method to keep track of your string length.
  1. The 2nd function called isPalindrome determines if the string entered is a palindrome. he function isPalindrome should return the number of palindromes found.
  • isPalindrome will call the function reverseStr described below.
  • isPalindrome will print the string and declare if it is a palindrome.
  • Finally print the length of the longest string found. This implies that the isPalindrome function calls the getString function.
  1. The 3rd function called reverseStr will reverse a string.
  • Do not use any library functions, you must build your own reverse algorithm.
  • The function reverseStr should return: 1 if the original and reversed strings are the same. 0 if the original and reversed strings are different.

Here are my questions:

  1. Can I call a string from function1 into function2 without putting them into main?... (is that the purpose of static variables)?

  2. When I call my functions into main should it literally look like this?:

     `main(void)
    {
     int function1();
    
     int function2();
    
     int function3();
    
     return 0;
    }`
    
  3. Why doesn't this output this greatest string length? Why does it keep saying 'i' is an undeclared identifier?

    `if(wordinput[i] > wordinput[i] - 1)
        printf("%s", &wordinput[i] > wordinput[i]);
    else
        break;`
    

It doesn't click in my head how functions are used to connect with each other. I understand the concept behind them, but when I put it into practice my brain refuses to make sense of it. I've scrapped and re-scrapped this so many times. Please help me.

CodePudding user response:

The assignment is defective. You should write reasonable code that performs the indicated task but ignore some of the conflicting requirements.

First, consider this constraint:

  1. DO NOT use pointers, they are not allowed for this exercise.

This is impossible. First, we will look at a pedantic interpretation the teacher probably did not intend, but it gives us a clue about their thinking. The reason this constraint is impossible is that the assignment clearly requires calling functions. However, calling functions in C (base C, without extensions, and I am unaware of any extensions that would be exceptions to this) requires using pointers. This is because C 2018 6.5.2.2 1 gives a constraint for function calls:

The expression that denotes the called function shall have type pointer to function…

It has to be a pointer. When you write printf("Hello, world.\n");, printf designates a function, but it is automatically converted to a pointer to the function, and that pointer is used for the function call.

This tells us the teacher was probably thinking superficially about the language and not about the automatic conversions that occur. This is a hint that maybe they were also not thinking about the automatic array conversions that occur. Maybe you are not supposed to use pointers explicitly, but it is okay to declare functions with array parameters (even though those parameters will be automatically adjusted to be pointers) and to call functions with array arguments (even though those arrays will be automatically converted to pointers to their first elements).

Here is another conflict. One statement says:

… getStrings will accept COUNT strings from the user

and another says:

… You may use a static variable if you call getStrings multiple times.

But, if getStrings accepts COUNT strings, that is all the program needs, so only one call is needed, so why would we be calling it multiple times?

Also, consider this:

You may use a static variable if you call getStrings multiple times. This is the easiest method to keep track of your string length.

That does not make sense to me. What does using a static variable or calling getStrings multiple times have to do with keeping track of your string length? You can keep the length in a static variable or an automatic variable, and getStrings either provides that length or you figure it out some other way, and whether you call getStrings multiple times or not has nothing to do with that.

Anyway, you can start with the third function. It looks like you are at a point where students are working with fixed-length arrays, rather than dynamically adapting to string lengths, so pick some maximum string size and define a constant for that, maybe #define MaximumStringSize 31. (The assignment says 30, but it is not clear whether that includes the terminating null byte or not.) Declare reverseStr with int reverseStr(char String[MaximumStringSize]). The assignment says it is supposed to reverse a string, so write code for it that will reverse a string. It does not say to do that in-place, so an easy thing to do is define a temporary array of size MaximumStringSize, find the length of the string, and copy characters from the source string into the temporary string, but backwards. And add the terminating null character.

Then compare the source string and the temporary string, and return 1 or 0 according to whether the strings are the same or different.

Then write isPalindrome. In it, define an array of COUNT arrays of MaximumStringSize of char. Call getStrings and pass it that array. Then iterate through the array and call isPalindrome on each element. While doing that, you need to print each string, print whether it is a palindrome and, if it is a palindrome, increment a count of palindromes found and do something to remember the longest length seen of any of the elements that is a palindrome.

After the loop, print the length of the longest palindrome found. (The assignment says “print the length of the longest string found.” I suspect that is another error by the teacher, and they want the length of the longest palindrome found. I might cover my bases by printing both of those.)

Finally, write getStrings. For the above, it can be declared as void getStrings(char Strings[COUNT][MaximumStringSize]);.

Note the assignment says “A string can be 1 or more words enclosed by double quotes.” This means you cannot read them with scanf(" s", words[i] as suggested in a comment. Something like scanf(" \"%[^\"]\"", Strings[i]) might work. (That’s a shortcut/kludge; there are quality issues, but it may be good enough for this assignment.)

CodePudding user response:

Just a very simple tip: Look at the specification again and try to implement it step by step. Note that you need to implement 3 additional functions. As you probably know, each function has a return type and you can call a function and store its return value in a variable.

CodePudding user response:

Write your program gradually: write a little code, compile the program and fix whatever errors you find, then run and fix whatever issues you find. Rinse and repeat.

int main(void) {
}
#include <stdio.h>

#define COUNT 5
#define MAX_STRING 30

void getStrings() {
   for(int i = 0; i < COUNT; i  ) {
     fgets(..., MAX_STRING, stdin);
   }
}

int main(void) {
   getStrings();
}

We try to compile that it will fail as it doesn't know what ... is so we need to either allocating memory for the aray of string in main() or you allocate the strings in getStrings(). As we cannot use calloc() / malloc() in getStrings() so let's do it in main():

#include <stdio.h>

#define COUNT 5
#define MAX_STRING 30

void getStrings(char words[COUNT][MAX_STRING]) {
   for(int i = 0; i < COUNT; i  ) {
       fgets(words[i], MAX_STRING, stdin);
   }
}

int main(void) {
   char words[COUNT][MAX_STRING];
   getStrings(words);
}

You compile your program and it's able to read 5 strings.

  1. The requirement says "The function should return the length of the longest string the user entered." so let's do that:
#include <string.h>

size_t getStrings(char words[COUNT][MAX_STRING]) {
   size_t max_length = 0;
   for(int i = 0; i < COUNT; i  ) {
     fgets(words, MAX_STRING, stdin);
     size_t current_length = strlen(words);
     if(current_length > max_length)
         max_length = current_length;
   }
   return max_length;
}
  1. Next thing is a hint "You may use a static variable if you call getStrings multiple times. This is the easiest method to keep track of your string length." Hmm... so the problem description is ambiguous as the first thing suggest it is reading 5 strings but this that it's reading one string. Let's change it to match the hint:
#include <stdio.h>
#include <string.h>

#define COUNT 5
#define MAX_STRING 30

size_t getStrings(char word[MAX_STRING]) {
    static size_t max_length = 0;
    fgets(word, MAX_STRING, stdin);
    size_t current_length = strlen(word);
    if(current_length > max_length)
        max_length = current_length;
    return max_length;
}

int main(void) {
   char words[COUNT][MAX_STRING];
   for(int i = 0; i < COUNT; i  ) {
        size_t max_length = getStrings(words[i]);
        // let's see if max_length works...
        printf("%zu\n", max_length);
   }
}

Let's see what it returns:

a
a
 2

Oh... that weird it puts a newline after a and then the space plus the line count. We need to remove the newline or use scanf instead.

  1. Let's fix the newline.
size_t getStrings(char word[MAX_STRING]) {
    static size_t max_length = 0;
    fgets(word, MAX_STRING, stdin);
    size_t current_length = strlen(word);
    word[--current_length] = '\0'; // end string at newline
    if(current_length > max_length)
        max_length = current_length;
    return max_length;
}

and now when we run the program it returns what we expect:

a
a 1

CodePudding user response:

Edit: the fact that you mark every response as not useful indicates you are simply looking for someone to do your assignment. Grow up and stop wasting people's time.

If you are struggling with the most basic concept of what a function is, you need to take a step back and consider if 1) Have you put in any real time thinking about this? 2) Are you in the wrong class? coding is not for everyone.

If you can understand the task at hand (i.e. given some type of input, and some conditions or rules to apply to this input, the output would be xyz), then you already answered what a function is. The function has a name, one or more input parameters to match the input, the code that performs the functions purpose (i.e uses the conditions/rules to do something with the input, and do something with the result of that processing). In some cases, the function returns the output. In other cases, the function simply prints the output or some message to std out or a log.

If the problem requires taking the output from task 1, and applying additional logic/processing of it, repeat the first exercise by writing a 2nd function.

When you run a program, it needs a starting place. Usually this is called the main or index script. This script can start the chain of events by taking input from user or a file or whatever is needed based on the requirements. How did you solve the first task? You started by passing the input to what ended up being function 1. So in your main script, take the input and call this function. If the function returns output that is required as input to your second (or any other functions you create), in pseudo code it looks like

output=functionone(input);
output2=functiontwo(output);

Functions are simply a means to organize your code into understandable, manageable, and reusable pieces, with defined expectations of what input parameters it require, and optionally what it returns. If some bit of code is required in many different places, make a function with that code so that later on if you have to change the logic, you dont have to change the many places - you only have to change the function.

If you know how to code the problem such that you achieve the expected output based on the input, as defined in your project, write the code without any functions in your main script. If you can achieve that, re-organizing it into functions is just a matter of reorganizing/refactoring. If you cannot write the program without functions, the problem has nothing to do with functions, but many other possibilities (i.e. lack of problem solving skills, coding isn't for everyone, not putting in enough effort, laziness, all of the above).

I hope this helps.

  • Related