Need help with a small program
I am a programmer in learning and i have a problem.
I use visual studio 2015 and in language 'C' i have to make a program which entered array of char's sorts into ascending order, prints out only Roman numerals out of it ('I','X','V'...) and an array without those numerals. Total of 3 prints. I would really appreciate if someone would write down the code since i tried many times and failed to make it. Also try using only for's and if's since i can use those only .
Code example:
Code:
#include <stdio.h>
#define MAX_BR_EL 15
void main()
{
int i, p, j, s, n;
while (1) {
printf("Enter the array length:\n");
scanf("%d", &n);
if (n <= 0 || n > MAX_BR_EL) break;
char a[n];
printf("Enter the array:\n");
for (s = 0; s < n; scanf("%c", &a[s++]));
{
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++)
if (a[i] < a[j]) { p = a[j], a[j] = a[i], a[i] = p; }
}
printf("Arranged array:\n", a[s]);
}
if (a[s] == 'I' || a[s] == 'V' || a[s] == 'X' || a[s] == 'L' || a[s] == 'C' || a[s] == 'D' || a[s] == 'M')
{
printf("Array of Roman numerals:\n");
printf("%c\n", a[s]);
}
else
{
printf("Array without Roman numerals:\n");
printf("%c\n", a[s]);
}
}
}
Re: Need help with a small program
The size of an array has to be defined at compile-time, not run-time.
As array a is to be used outside of the while loop, it needs to be defined outside as well.
Code:
printf("Arranged array:\n", a[s]);
This is not how you display the array. You'll need a loop to display the array elements.
Your test for roman numerals / display is also outside of any loop
Re: Need help with a small program
I tried putting this :
Code:
printf("Arranged array:");
for (s = 0; s < n; s++)
printf("%c\n", &a[s])
but the prints are a mess.
Re: Need help with a small program
The ampersand as used there gives you the address of a variable.
You should get out of the habit of single character, meaningless variable names, and putting multiple statements on a single line. It makes code impossible to understand and debug.
Re: Need help with a small program
Thanks,did not notice that. Also is my comparison code good? Have you noticed anything else that needs fixing?
Re: Need help with a small program
Code:
printf("Arranged array:");
for (s = 0; s < n; ++s)
printf("%c", a[s]);
For roman
Code:
const char roman[] = "IVXLCDM";
...
if (strchr(roman, a[s]))
//Got a roman
else
//Not a roman
Re: Need help with a small program
Quote:
Have you noticed anything else that needs fixing?
Why the while loop? If this is for looping to repeat ask for input and display until invalid input and exit then the loop scope is wrong - otherwise what it's purpose?
Code:
obtain data
sort data
display as required
PS how are you dealing with the \n entered as part of the array length?