Palindrome using recurison - c

The following code needs to check for palindromes and write the user input backwards using recursion, and then find the Greatest Common Denominator using the same method. The code section that finds the gcd and tells whether or not it is a palindrome works, but it crashes every time it gets the the part where it reverses the code. Why is it crashing every time.
#include <stdio.h>
#include <stdlib.h>
/*Delare the prototypes*/
char palindromes(char[], int);
char backwards(char[], int, int);
int gcdfunc(int, int);
int findgcd(int, int);
int main ()
{
char userinput[10];/*Declares the character array for the input*/
int index= 0;/*Index for the counting loop*/
int counter= 0;/*Counts number of elements entered in the array*/
int printindex= 0;/*Index to print the values on the screen*/
int gcd= 0;/*Sets a value for the GCD*/
int palcheck = 0;
int value1= 0;/*User value 1*/
int value2= 0;/*User value 2*/
int flipindex=0;/*Sets an index for the gcd function*/
printf("Please enter a series of nine or less characters to test for a palindrome.\n");
scanf(" %9s%n", &userinput, &counter);
printf("\n");
palcheck = palindromes(userinput, counter-1);
if(palcheck == 0)
{
printf("Your input was not a palindrome \n");
}/*End of if statement*/
else
{
printf("Your input was a palindrome \n");
}/*End of else statement*/
backwards(userinput, counter-1, flipindex);
printf("Your input backwards is: ");
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
printf("\n");
printf("\nEnter two numbers: ");
scanf("%d %d",&value1,&value2);
gcd=gcdfunc(value1, value2);
printf("The GCD of %d and %d is: %d",value1,value2,gcd);
system("pause");
}/*End of main function*/
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
char backwards(char userinput[], int counter, int flipindex)
{
while(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex];
userinput[counter-flipindex] = temp;
backwards(userinput, counter, flipindex++);
}
}/*End of reverse function*/
int gcdfunc(int value1, int value2)
{
int gcd;
gcd=findgcd(value1,value2);
return gcd;
}
int findgcd(int value1,int value2)
{
while(value1!=value2)
{
if(value1>value2)
return findgcd(value1-value2,value2);
else
return findgcd(value1,value2-value1);
}
return value1;
}

in your function there is no pass for the variables and it stays in the same cycle over and over and in recursion the same function does not share the same variables it create new one and if you modify one it does not affect the others variables.
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
So here is the code i did
int palindromes(char userinput[], int counter,int index , int palendex)
{
if(userinput[palendex] == userinput[index])
{
if(counter%2 == 0 && ( index - palendex) == 1)
return 0;
if( index == palendex )
return 0;
else
return palindromes(userinput, counter , index-1 ,palendex+1 );
}
else
return 1;
return 1;
}
In your backward function is that it never leaves the cycle while and do a lot of instances that the memory available runs out. so I changed it to an if statement and it looks like this (and a few changes)
int backwards(char userinput[], int counter, int flipindex)
{
if(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex-1];
userinput[counter-flipindex-1] = temp;
backwards(userinput, counter, flipindex+1);
}
return 1;
}

It looks like you go past the end of the buffer with this code:
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
because printindex == counter and userinput[counter] is out of bounds. Try this for-statement instead:
for(printindex; printindex < counter; printindex++)

if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
It call recursively condition in the if statement is not satisfied. but It will stack overflow repeated calls indefinitely because there is no change in the situation.

Related

Check if the user input matches one of the elements in the array

If the user inputs a value that matches with an int in the array continue the program else quit the program.
My issue is that the function loops the whole array and if it finds one of the values doesnt match it will quit.
//Check if the user input matches with one of the ints in the array
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] != num) {
printf("Invalid input");
exit(0);
}
}
}
void main() {
int arr[3] = { 1, 2, 3 };
int num = 0;
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
printf("\nPLease enter a value which matches with the array %d", num);
scanf("%d", &num);
check(num, arr);
}
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] == num) {
return;
}
}
printf("Invalid input");
exit(0);
}
Your issue is that checks a single element and judges the input on that specific value. If it has run through each value and the function has still not returned, there is not match and we can exit the program.
You have a logic flaw in the check function: you should output the message and quit if none of the values match the input. You instead do this if one of the values does not match. The check always fails.
Here is a modified version:
#include <stdio.h>
//Check if the user input matches with one of the ints in the array
void check(int num, const int arr[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (arr[i] == num) {
// value found, just return to the caller
return;
}
}
// if we get here, none of the values in the array match num
printf("Invalid input: %d\n", num);
exit(1);
}
int main() {
int arr[3] = { 1, 2, 3 };
size_t len = sizeof(arr) / sizeof(*arr); // length of the array
int num;
for (size_t i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Please enter a value which matches with the array: ");
if (scanf("%d", &num) == 1) {
check(num, arr, len);
} else {
// input missing or not a number
printf("Invalid input\n");
}
return 0;
}
You are right, you do exit once arr[i] != num (When the value is not the same as the i:th element in the array).
So, you could change it to: arr[i] == num. If it is the same, perhaps print "You got it!", and a return afterwards.

Factorial program in c

Trying to make a code that gets the factorial of the inputted number.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
int main()
{
int endvalue, numA, numB;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA, numB);
printf("%d", endvalue);
return 0;}
getch();
return 0;
}
For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)
int factorial(int number, int i)
{
for(i = number - 1; i>0; i--){
number = number * i;
}
if (number == 0) {printf("1");}
return number;
}
Is there anything I missed in the code that's causing these errors?
A definiton of factorial is:
factorial(0) = 1
factorial(n) = n * factorial(n-1)
Note: Factorial is legal only for number >= 0
In C, this definition is:
int factorial(int number)
{
if (number < 0)
return -1;
if (number == 0)
return (1);
/*else*/
return (number * factorial(number-1));
}
#include <stdio.h>
#include <string.h>
int factorial(int number)
{
int endval=1;
for(int i = number ; i>0; i--){
endval *= i;
}
return endval;
}
int main()
{
int endvalue=0;
int numA=0;
char userchoice[1];
printf("Enter a choice to make (f for factorial): ");
int ret=scanf("%s", userchoice);
if (!ret){
printf("Error in scanf: %d", ret);
}
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getchar();
return 0;
}
Code with some changes will work
factorial() function can get only one argument.
As a good habit all variables must be initialized.
Add include statement to source and be explicit not rely on compiler.
As we use strcmp() we must include string.h
use standard getchar() instead of getch()
Also can check return value of library function scanf() to ensure reading is correct or not.
You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.
There are possibly few things to correct. See please attached code.
int factorial(int number)
{
if (number == 0){ return 1; }
int endval=1, i;
for(i = 1; i<=number; i++) { endval *= i; }
return endval;
}
int main() {
int endvalue, numA;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0) {
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getch();
return 0;
}

How to remove the last comma in comma separated prime numbers within a range?

I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated

Is this code correct for checking for prime number in c using functions?

Is this code correct for checking prime number using functions. I am not getting any syntax errors but it is always showing prime regardless of what I enter.
#include<stdio.h>
int prime(int);
void main() {
int n, count, a;
printf("enter the number\n");
scanf("%d", &n);
prime(n);
if (count == 2)
printf("prime");
else
printf("not prime");
}
int prime(int n) {
int i, count = 0;
for (i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
return (count);
}
}
Modify your function prime -
int prime(int n) {
int i, count = 0;
for (i = 1; i <n; i++) { // go till n (or better till sqrt of n)
if (n % i == 0) {
count++;
}
if(count==2){ // if count is 2 get out of loop
break;
}
}
return count; // return out of loop
}
In you function main-
1. void main -> int main(void)
2. write you if else satatements as follows -
if (count == 2)
printf("not prime");
else
printf("prime");
3. initialize count to 0 in main.
call function as -
count=prime(n);
Your prime function doesn't work properly. In the first for loop you're doing n & 1 == 0 which always is true, and in the last loop n % n == 0 also is always true
int prime(int n){
int i;
int isPrime = 1;
for(i=2;i<sqrt(n) && isPrime;i++){ // do the loop while 2<i<sqrt(n) and n isPrime, once you know it's not prime don't loop anymore
isPrime = n%i; // If it's 0 then it's not prime (isPrime = 0) else it's true
}
return isPrime;
}
Edit: Optimized the for loop until i=sqrt(n)
/* i just needed to take input of value count and store it in a variable*/
#include<stdio.h>
int prime(int);
int main(void)
{
int n,count,a,m;
printf("enter the number\n");
scanf("%d",&n);
m=prime(n);
if(m>2)
printf("not prime");
else
printf("prime");
}
int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
return(count);
}
A simple function return true if the number is prime and false if not.
int prime(int n){
int i;
for(i= 2; i < n; i++){
if(n % i ==0 && i != n)
return true;
}
return false;
}

Memory can't be read when shortest function is run

I had a bunch of problems with this program but looks like this might be inches away from completion and I was hoping someone could tell me what the hell's wrong with the blasted thing!
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING], int);
int shortestArray(char [][SIZE_OF_STRING], int);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[1000][SIZE_OF_STRING];
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
n++;
printf("Enter %d names", n - 1);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array, n);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array, n);
printf("Shortest name is %s in position %d\n", array[position], position + 1);
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
gets(a[i]);
}
}
void printArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
puts(a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i;
int chag = 0;
int position;
while (a[i] != '\0')
{
if (strlen(a[i]) < strlen(a[i-1]))
{
position = i;
chag = 1;
}
else
{
if (chag = 0)
{
position = 1;
}
else
{
printf("");
}
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}
only worried about "shortest" function at the moment all others run okay.
I also know there are better ways of doing the search but I keep getting "declaration creates integer from pointer without cast" errors when I change to a more standard search with a default smallest etc.
chag is to say whether or not number one in a[] is the smallest as it never gets checked, going to change this as soon as I get it working as I can see a more effective way of doing it.
[edit]
My bad, the error that appears is an application error when "smallest" is selected.
the following appears
"the instruction at "0x77c478c0" referenced memory at "0xd2fd82e0". the memory could not be "read".
ok to terminate program, cancel to debug.
changed the shortest function to the following and still get a similar memory message;
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i = 1;
int position = 1;
while (a[i] != '\0')
{
if (strlen(a[i + 1]) < strlen(a[i]))
{
position = i + 1;
i++;
}
else
{
i++;
}
}
return position;
}
There's a clbuttic typo in shortestArray():
if (chag = 0) {
position = 1;
}
// ...
This will always evaluate to false, so the else block is run.
Here, zero is assigned to chag which makes the expression evaluate to zero (false). Use the comparision operator == instead. You might want to crank up warning levels as I'm sure, any C compiler has an appropriate message for this.
One big and obvious problem is that in the function you use the variable i without initializing it.
Another problem is this expression: strlen(a[i-1]). If i is 0 then this will access memory before the array.
In addition to the other answers so far:
You don't increment i either.
If I imagine all the trivial fixes applied (correct iteration, comparison instead of assignment in the condition), the function is going to return position of last local minimum of length. I.e. having list of strings like
"a", "bbbb", "ccc", "dd"
it will return 3, but shortest string is at position 0!
You do remember array indices in C start from 0, right (in position = 1)?
you have to know the number of strings entered in the array to avoid unknown behavior.
a way to do this : in main, just after declaration of array, put :
strcpy(array[0], ""); // to indicate that the array is empty.
in the end of readArray() :
strcpy(a[n] , ""); // there is n strings written bythe user (a[0] to a[n-1]).
and finally :
in shortestArray(), the stop condition of the loop must be changed to :
while (strcmp(a[i],"") != 0 ) //a[i] == '\0' is not correct because a[i] is string and '\0' is char.
here is the entire code with the changes i made :
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
#define SIZE_OF_ARRAY 1000
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING]);
int shortestArray(char [][SIZE_OF_STRING]);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[SIZE_OF_ARRAY][SIZE_OF_STRING]; //change here !
strcpy(array[0] , ""); //instruction added : means array is empty
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
while (n >= SIZE_OF_ARRAY)
{
printf("the number you entered is bigger than the maximum number of strings, please enter a number smaller than %d\n", SIZE_OF_ARRAY);
}
printf("Enter %d names", n);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array);
if (position == -1)
printf("there is no string entered !\n");
else
printf("Shortest name is %s in position %d\n", array[position-1], position );
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
scanf("%s",a[i]);
}
strcpy(a[n] , "");
}
void printArray(char a[][SIZE_OF_STRING])
{
int i;
for (i=0; i< SIZE_OF_ARRAY; i++)
{
if (strcmp(a[i] , "") == 0) // a[i-1] is last string entered
break; // this avoid printing non initialized string causing unknown behaviour.
printf("%s\n",a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING])
{
int i = 0;
int position = 1;
if(strcmp (a[i] , "\0") == 0)
return position = -1; // there no string entered.
while (strcmp (a[i+1] , "\0") != 0)
{
if (strlen(a[i+1]) < strlen(a[i]))
{
position = i+2 ;
i++;
}
else
{
i++;
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}

Resources