order two names in alphabetical order - c

I've got an essay where is says "Given name and number of votes of two candidates, make two charts which one is sorted by the number of votes increasing, and the other in alphabetical order."
I've done the first part of the code already, and it's something like this:
#include <stdio.h>
int main () {
char candidato1[50], candidato2[50];
int voti1, voti2;
scanf("%s", &candidato1);
scanf("%s", &voti1);
printf("Ordine basato sul numero di voti in verso cresciente\n");
printf("%-10s %-10s\n", "Nome" "Numero di voti",);
if (voti1>voti2) {
printf("%-10s %-10d\n", candidato1, voti1);
printf("%-10s %-10d\n", candidato2, voti2);
}else {
printf("%-10s %-10d\n", candidato2, voti2);
printf("%-10s %-10d\n", candidato1, voti1);
}
printf("\n");
printf("Ordine alfabetico\n");
printf("%-10s %-10s\n", "Nome" "Numero di voti",);
//alphabetical order here
return 0;
}
As I've said in my previous post, I'm still new to c, and char are really a mystery for me. I've did some searches online but I couldn't find anything useful or clearly understandable for me. Hope someone here can help me figure it out.

You could use strcmp function from string.h to compare strings in alphabetic manner. If it returns number > 0 than first string is greater then second, similarly, if it returns number < 0 than second string is greater then first, otherwise if it returns 0 than the strings are equal.
It would look like that:
if (strcmp(candidato1, candidato2) > 0) {
printf("%-10s %-10d\n", candidato1, voti1);
printf("%-10s %-10d\n", candidato2, voti2);
} else {
printf("%-10s %-10d\n", candidato2, voti2);
printf("%-10s %-10d\n", candidato1, voti1);
}
Do not forget to #include <string.h>

Related

Unwanted output on second pass using strcpy

I'm reading a book called "C programming Absolute Beginners Guide."
The following program uses some if loops and strcpy to store some character arrays provided by the user. The first pass of strcpy works fine. The second produces garbage. I understand the array needs a \0 to end. According to the book, strcpy does this automatically. What am I missing?
#include <stdio.h>
#include <string.h>
main()
{
int ctr, numMovies, rating, favRating, leastRating;
char movieName[40], favorite[40], least[40];
favRating = 0;
leastRating = 0;
do {
printf("How many movies have you seen this year? ");
scanf(" %d", &numMovies);
if (numMovies < 1)
{
printf("No movies! How can you rank them?\nTry again\n\n");
}
} while (numMovies < 1 );
for (ctr = 1; ctr <= numMovies; ctr++)
{
printf("\nWhat's the name of the movie? ");
printf("(1-word titles only!) ");
scanf(" %s", movieName);
printf("On a scale of 1 to 10, what would ");
printf("you rate it? ");
scanf(" %d", &rating);
if (rating > favRating)
{
strcpy(favorite, movieName);
favRating = rating;
}
printf("%s", movieName);
if (rating < leastRating)
{
strcpy(least, movieName);
leastRating = rating;
}
}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;
}
Because you initialize leastRating to zero you won't have a least favorite unless the rating is negative. Not sure that's what you want.
The best suggestion is from #xing, add a include
#include <limits.h>
and initialize you best and worst like this;
favRating = INT_MIN;
leastRating = INT_MAX;

Number guessing game in C

I had a problem at doing my number guessing game in C. While running the program it shows up return function when I put the char element in there. Can someone help me with this? Also how can I improve my code in order to make it workable? I'M really stuck with this issue.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main()
{
char s, n, q;
int b;
bool (1=true), (0=false);
int secret;
secret = rand();
int guess;
int seed;
srand(seed);
printf("Welcome to the guessing game!\n");
do{
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
if((s==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
}
else if((n ==1))
{
printf("Enter a new MAXIMUM\n");
scanf("%s", rand());
if(( s ==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
printf("The secret number is between 0 and rand() Guess:");
scanf("%s", b);
if(guess = rand()){
printf("Congratulations you won, You took %d guesses!", b);
break;
}
else if(guess > rand())
{
printf("Too High, Guess again:");
}
else if(guess < rand()){
printf("Too Low, Guess Again:");
}
else{
printf("This number out of the number set!");
}
}
}
else{
printf("Unrecognized command");
}
}while(q == 1);
printf("You quited the game");
return 0;
}
This code has myriad issues to resolve. I'd suggest approaching your code writing process in small steps. It appears as though you wrote the entire program in one burst, ran it, and found it didn't work instead of incrementally adding small features and running each one to verify it works before moving on to the next step. Not doing this results in a difficult to debug program and a lack of understanding about how the program operates.
To be specific, try writing a three or four line program that collects and prints user input. Is the output working as you expect? Did you test its robustness on a variety of input? Can you write it to use a variety of data types? If something isn't working, did you research the problem and resolve it before steaming ahead?
Some areas of your program to investigate:
bool (1=true), (0=false); doesn't compile and isn't necessary for the program. If you #include <stdbool.h> you don't need to do this (you can simply write if (something == true)).
srand() is not properly called or seeded. Seed it once per program using the time() call from the header you included and call rand() once per game. Use the % operator to set the function output between 0 and max.
On each turn, compare guess against the value you previously stored rand() in rather than calling rand() during each comparison, which makes the game logic arbitrary.
%s input isn't appropriate; read chars %c and ints %d, passing appropriate variable references to scanf. scanf("%s, %s, %s", s, n, q); collects 3 whitespace separated strings for input instead of 1 char as the prompt suggests.
There is no game loop. Add an inner loop to run a game when the user chooses s and move your guess/response logic there.
Use more verbose variable names and correct brackets and indentation to improve readability.
Putting it all together, here's one possible working version. It could make better use of functions and implement secure user input (exercises for the reader):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char menu_choice;
int guess;
int guesses;
int secret;
int max = 100;
srand(time(NULL));
printf("Welcome to the guessing game!\n");
for (;;) {
printf("\nMenu: (s) to start a new game, (n) to set a new range, or (q) to quit: ");
scanf(" %c", &menu_choice);
if (menu_choice == 's') {
guesses = 0;
secret = rand() % max;
for (;;) {
printf("\nThe secret number is between 0 and %d. Enter a guess: ", max);
scanf("%d", &guess);
guesses++;
if (guess == secret) {
printf("\nCongratulations, you won! You guessed %d in %d guesses!\n", secret, guesses);
break;
}
else if (guess > secret) {
printf("Too high! Guess again.");
}
else if (guess < secret) {
printf("Too low! Guess again.");
}
else if (guess >= max) {
puts("Out of range");
}
}
}
else if (menu_choice == 'n') {
printf("\nEnter a new maximum: ");
scanf("%d", &max);
}
else if (menu_choice == 'q') {
puts("\nGoodbye!");
break;
}
else {
puts("\nUnrecognized command.");
}
}
return 0;
}
Sample run:
Welcome to the guessing game!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: n
Enter a new maximum: 50
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: s
The secret number is between 0 and 50. Enter a guess: 25
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 37
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 43
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 47
Congratulations, you won! You guessed 47 in 4 guesses!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: q
Goodbye!
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
you dont need to use three variables s,n,q. you should ask the user to enter a single choice. either to start a new game or to quit or aything else.
secondly, rand() returns a random number every time. you are supposed to store random number somewhere. like this
rand_num=rand()
also
if(guess = rand())
is a wrong way of comparison. this should be
if(guess==rand_num)
finally binary search is the solution for your problem. please refer it on internet

If statements not working inside while loop

Only the 'strlen' function is being executed by the program.
The if statements inside this while loop do not even work...
#include<stdio.h>
#include<string.h>
#include <ctype.h>
main()
{
char cMessage[100];
int cLow = 0, cUp = 0, cSpec = 0, cSpace = 0, cNum = 0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x = 0;
while(cMessage[x] != 0)
{
x = strlen(cMessage);
printf("Total characters: %d", x);
if(islower(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cLow);
cLow++;
}
else if(isupper(cMessage[x]))
{
printf("\nTotal Uppercase Letters: %d", cUp);
cUp++;
}
else if(isalnum(cMessage[x]))
{
printf("\nTotal Special Characters: %d", cSpec);
cSpec++;
}
else if(isspace(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cSpace);
cSpace++;
}
else if(isdigit(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cNum);
cNum++;
}
}
x++;
}
I cannot figure out the cause of this issue...
What may be the cause of this?
EDIT: So here's the revised code of the program, the only problem that I have now is that the spaces are not being counted. And btw, is there a specific function used to 'count' special characters? I've used 'isalnum' and I realized it was wrong
#include<stdio.h>
#include<string.h>
#include <ctype.h>
#include<conio.h>
main(){
char cMessage[100];
int cLow=0, cUp=0, cSpec=0, cSpace=0, cNum=0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x=0;
while(cMessage[x]){
printf("Total characters: %d", strlen(cMessage));
while(cMessage[x]!=0){
if(islower(cMessage[x])){ cLow++;}
if(isupper(cMessage[x])){ cUp++;}
if(isalnum(cMessage[x])){ cSpec++; }
if(isspace(cMessage[x])){ cSpace++; }
if(isdigit(cMessage[x])){ cNum++; }
x++;
}
printf("\nTotal Lowercase Letters: %d", cLow);
printf("\nTotal Uppercase Letters: %d", cUp);
printf("\nTotal Special Characters: %d", cSpec);
printf("\nTotal Spaces: %d", cSpace);
printf("\nTotal Numbers: %d", cNum);
getch();
}
}
The x = strlen(cMessage); will give you the length of cMessage which is always the index of the last item + 1.
for example if: cMessage = "The" and x = strlen(cMessage) , then:
x = 3
cMessage[0] = 'T'
cMessage[1] = 'h'
cMessage[2] = 'e'
cMessage[3] = NULL terminator // equivalence to 0
Note that there is usually a NULL terminator after the last character.
So as you can see, the while condition is always false after the first pass.
Try to use a separate variable to iterate through cMessage.
Also you need to consider putting variables like cUp++' before the 'printf statements.
A more elegant alternative will be using for statement instead of while.
Also note that isalnum(cMessage[x]) is interfering with if(isdigit(cMessage[x])) so, it is better to use separate if statements and git rid of else if, moreover, if you want to count special characters you have to negates isalnum to be: if(!isalnum(cMessage[x])).
At last your input will not accept sentences (word with spaces between them), so you have to consider replacing:
scanf("%s", cMessage);
with
scanf("%[^\n]s",&cMessage);
You take x as the lenght of your string. So that's one longer then your Array. After the full array is always a 0 to show the program the array is not longer. This way you can never go in the if's
cMessage[x] after x=strlen(cMessage) is always 0. String contains chars from 0 till x - 1, char at post x is 0. Thus any if-condition is false.
I suppose x=strlen(cMessage); is not needed and must be removed, x++ must be three last operator in the loop body, since you want to count chars of different kinds.
printf("Total characters: %zu", strlen(cMessage));
while(cMessage[x] != 0) {
if(islower(cMessage[x])) {
...
}
x++;
}
%d is not proper format for size_t type on 64-bit platform. Read this: How can one print a size_t variable portably using the printf family?

making a staircase of x's using loops in C, but I keep getting squares

So I need to make a staircase but I clearly have something wrong with my logic. Any advice on how to approach this? I only end up getting squares.
#include <stdio.h>
int main()
{
int a,b,z,y,p;
char x;
scanf("%i ", &a);
printf("Number of stairs is: %i\n", a);
printf("up: \n");
for(b=0; b<a; b++) {
for(z=1; a>=z; z++) {
x='x';
p=1;
if ((p=z)) {
printf("%c", x);
}
else {
printf(" ");
}
p++;
}
printf("\n");
}
}
Your code has many flaws and lack of clarity is one of them. Nevertheless, the reason you have a square is because p=z is always true (setting the value of p to z returns the value of z and this, in your code is always 1 or higher - a true value for C standards).
Here is a code that works, loosely based on your example:
#include <stdio.h>
int main() {
int numberSteps,currentStep,currentColumn;
scanf("%i", &numberSteps);
printf("Number of stairs is: %i\n", numberSteps);
printf("up: \n");
for(currentStep=0; currentStep<numberSteps; currentStep++) {
for(currentColumn=0; currentStep>=currentColumn; currentColumn++) {
printf("x");
}
printf("\n");
}
}
Please notice that I changed the variable names so that they became meaningful and also got rid of the unnecessary variables and the unnecessary test if ((p=z)) that was cluttering your code.

Why do I get random garbage values in this simple program?

I want to read some number from the terminal and print them afterwards.
However, they all seem to be some kind of random value instead of the one I supplied.
Why doesn't my input get saved correctly?
int main (void)
{
int i = 0 , numeros[21] , cont = 1, z = 0;
puts("\n === Bienvenido ===\n");
puts("\n === Vamos a procesadar un numero de serie de 20 digitos [Numericos] ===\n");
puts("\n === Dime los numeros ===\n");
while (cont != 20 )
{
fflush(stdin);
scanf("%d", &numeros[i]);
printf("\n === Dime otro numero. Numeros: %d ===\n", cont);
cont++;
}
for (z = 0; z < 20; z++)
{
printf("\nLos numeros son: %d\n", numeros[z]);
}
system("pause");
}
Ok, a couple of issues:
numeros is declared as an array of 21 ints, but you're using it as if it were numeros[20]
Undefined behaviour because you're calling fflush on stdin
scanf("%d", &numeros[i]), though unsafe, is all fine and dandy, but i is never incremented
Check return values of functions... always: scanf returns the number of values it scanned, if it returns 0, no %d was scanned, and numeros[i] needs to be reassigned.
Here's an example of how I'd write your program:
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
int c,i=0,
numbers[20],
count=0;
//puts adds new line
puts("enter 20 numbers");
while(count < 20)
{
c = scanf(" %d", &numbers[i]);//note the format: "<space>%d"
if (c)
{//c is 1 if a number was read
++i;//increment i,
++count;//and increment count
}
//clear stdin, any trailing chars should be ignored
while ((c = getc(stdin)) != '\n' && c != EOF)
;
}
for (i=0;i<count;++i)
printf("Number %d: %d\n", i+1, numbers[i]);
return 0;
}
You are not incrementing i in the first loop.
You are incrementing cont, but using numeros[i] to store your input. As i never changes, you only write to the first array element. Change the i to cont, as in
scanf("%d", &numeros[cont]);
What exactly do you want to achieve? I see that you're putting into i=0 index of your numeros array number from stdin. Then you're iterating trough this array, but you've just entered one number! You should propbably change the subsctript of your numeros array to cont like that:
scanf("%d", &numeros[cont]);
scanf("%d", &numeros[i]);
should be replaced with
scanf("%d", &numeros[cont]);
AS you are incrementing cont not i

Resources