I am learning from C Programming Absolute Beginner's Guide. I had to do the following exercise and I took it upon myself to try to add a:
"Would you like to sort these numbers in ascending order? (Y/N): "
after the numbers are randomly generated. However, I am struggling with this. I have tried if, else if, do while, etc. But I am struggling with it. How would you add that to this code?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ctr, inner, outer, didSwap, temp, choice;
int nums[10];
time_t t;
srand(time(&t));
//First step is to fill the array with random numbers (from 1 to 10)
for (ctr = 0; ctr < 10; ctr++)
{
nums[ctr] = (rand() % 99 + 1);
}
//Now list the array as it currently is before sorting
puts("\nHere is the list before the sort:");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%d\n", nums[ctr]);
}
//Now sort the array
for (outer = 0; outer < 10; outer++)
{
didSwap = 0; //Becomes 1 (true) if list is not yet ordered
for (inner = outer; inner < 10; inner++)
{
if (nums[inner] < nums [outer])
{
temp = nums[inner];
nums[inner] = nums [outer];
nums[outer] = temp;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}
//Now list the array as it currently is after sorting
puts("\nHere is the list after the sort:");
for (ctr = 0; ctr <10; ctr++)
{
printf("%d\n", nums[ctr]);
}
return 0;
}
EDITED CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ctr, inner, outer, didSwap, temp, choice;
int nums[10];
time_t t;
srand(time(&t));
//First step is to fill the array with random numbers (from 1 to 10)
for (ctr = 0; ctr < 10; ctr++)
{
nums[ctr] = (rand() % 99 + 1);
}
//Now list the array as it currently is before sorting
puts("\nHere is the list before the sort:");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%d\n", nums[ctr]);
}
puts("Would you like to sort in ascending order? ");
puts(("(Reply Y or N): "));
scanf(" %d", choice);
choice = toupper(choice);
if (choice = 'Y')
{
//Now sort the array
for (outer = 0; outer < 10; outer++)
{
didSwap = 0; //Becomes 1 (true) if list is not yet ordered
for (inner = outer; inner < 10; inner++)
{
if (nums[inner] < nums [outer])
{
temp = nums[inner];
nums[inner] = nums [outer];
nums[outer] = temp;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}
//Now list the array as it currently is after sorting
puts("\nHere is the list after the sort:");
for (ctr = 0; ctr <10; ctr++)
{
printf("%d\n", nums[ctr]);
}
}
else if (choice = 'N')
{
puts("Have a good day!");
}
return 0;
}
You should use %c format specifier with char variable to read one character.
You will have to use unary & operator to get a pointer to a variable for scanf().
= is an assignment operator in C. You should use == operator to check equality.
/* remove choice from int variable declaration */
char choice; /* use char */
puts(("(Reply Y or N): "));
scanf(" %c", &choice); /* use %c and & */
choice = toupper(choice);
if (choice == 'Y') /* use == */
{
//Now sort the array
/* omit */
}
else if (choice == 'N') /* use == */
{
puts("Have a good day!");
}
Related
I need to make a program that stores numbers inside of an array. But it must have no duplicate elements.
int x;
int z[8];
for( x = 0; x<8;x++)
printf("number: ");
scanf("%d",&z[x]);
}
for( x=0;x<8;x++) {
printf("%d ",z[x]);
}
First, initialize the array, so that you do not end up reading an uninitialized value and fail the test.
int user_nums[6] = {0};
Next, you need to have another check in the for loop, to read the number again if it is a duplicate.
The code will look like this.
#include<stdio.h>
int main(){
int x,y;
int exists = 0;
int user_nums[6] = {0};
for( x = 0; x<6;x++){//for loop to get the players selected numbers
do {
exists = 0;
printf("Enter a number(from the #'s 1-42): ");
scanf("%d",&user_nums[x]);
for(y =0; y < x; y++) { //to check for duplicates
if (user_nums[x] == user_nums[y])
{
printf("Number already exists\n ");
exists = 1;
break;
}
}
}while (user_nums[x]<1 || user_nums[x]>42 || exists);//accepts only numbers from 1-42 which are not duplicates (continous to ask you for a number until condition is met).
}
printf("Your numbers: \n");
for( x=0;x<6;x++){
printf("%d ",user_nums[x]); // prints the numbers you inputed.
}
return 0;
}
The following code could work in O(n):
#include<stdio.h>
int main()
{
int user_nums[6];
int index[50];
for (int i = 0; i != sizeof(index) / sizeof(index[0]); ++i)
index[i] = -1;
for (int i = 0; i < sizeof(user_nums) / sizeof(user_nums[0]); ++i) {
for (;;) {
printf("Enter a number(from the #'s 1-42): ");
scanf("%d", user_nums + i);
if (user_nums[i] < 1 || user_nums[i] > 42) {
printf("wrong number\n");
continue;
}
if (index[user_nums[i]] != -1) {
printf("dump number\n");
continue;
}
index[user_nums[i]] = i;
break;
}
}
printf("Your numbers: \n");
for(int i = 0; i < 6; ++i)
printf("%d ", user_nums[i]);
return 0;
}
I have a coding assignment for my CIS class. The assignment is to write a program the will create an array of structures that will hold information on at max 10 dogs. At the end of the program, you are supposed to sort the array of dogs by either name or size. But I am unable to code the sorting of the array of dog. I was wondering how to sort the array of dogs for later use in the main function.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dog{
char name[20];
int weight;
int age;
int ageDogYears;
char size[7];
};
typedef struct Dog DG;
void calc(DG[], int);
void sort(DG[], int);
void display();
int main(){
DG dArray[10];
int x = 0;
char str[80], *i;
FILE *inFile;
inFile = fopen("dogfile.txt", "r");
if (inFile == NULL){
printf("Error opening file");
exit(1);
}
while(fgets(str, 80,inFile) != NULL){
i = strtok(str, ", ");
strcpy(dArray[x].name, i);
puts(dArray[x].name);
i = strtok(NULL, ", ");
dArray[x].weight = atoi(i);
printf("%d\n", dArray[x].weight);
i = strtok(NULL, ", ");
dArray[x].age = atoi(i);
printf("%d\n", dArray[x].age);
x++;
}
calc(dArray, x);
sort(dArray, x);
return 0;
}
void calc(DG dog[], int numDogs){
int y, i, total;
for(i = 0; i < numDogs; ++i){
if(dog[i].weight <= 20){
//sets the dog size to small
strcpy(dog[i].size, "Small");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 15;
else if(y == 1)
total += 8;
else if(y == 2)
total += 5;
else
total += 4;
}
}
else if(dog[i].weight <= 50){
//sets the dog size to medium
strcpy(dog[i].size, "Medium");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 14;
else if(y == 1)
total += 9;
else if(y == 2)
total += 7;
else
total += 5;
}
}
else{
//sets the dog size to Large
strcpy(dog[i].size, "Large");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 12;
else if(y == 1)
total += 9;
else if(y == 2)
total += 8;
else
total += 7;
}
}
dog[i].ageDogYears = total;
total = 0;
}
}
void sort(DG dog[], int numDogs){
int sortType, i, y, temp;
printf("\n wlould you like to sort by name(N) or size(S): ");
scanf("%c", &sortType);
switch(sortType){
case 'N': case 'n':
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs); ++y){
if(dog[y].weight > dog[y+1].weight){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
break;
default:
if((sortType != 's') && (sortType != 'S'))
printf("\n invalid input! Setting sort type to size.");
//sorting of dog names
}
}
Sample Input
Fluffy,23,6
Fido,65,7
Pepper,44,5
Bowser,75,10
Victor,10,2
Sassy,51,1
Any help would be much appretated! Thanks.
In my opinion, your error resides (despite of other comments I'll do below) in specifying %c as format descriptor to pass a pointer to int to match. You have to pass a pointer to char to make scanf(3) to select the proper place to put the character into. You probably are not getting the right character or no character at all (this leads to Undefined Behaviour in your program)
Some other problems are that you are using the weight field of the structure when requested to sort by name (on n input char) and other errors like this. This includes that you use y < (numDogs) in the inner loop limit condition (it must be y < (numDogs - 1), or you'll compare the y-esim with the y+1-esim element (out of array bounds)
Also, as you are using the same algorithm for both sorting options, I should include the switch statement inside the inner loop (where you do the comparison) as doing otherwise will force you to copy the same sorting code twice (for the overall sorting algorithm), as in:
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs - 1); ++y){
int sortResultGreater;
switch (sortType) {
case 'n': case 'N':
sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0;
break;
default: { /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
static int not_already_printed = 1;
if (not_already_printed) {
printf("Error, sortType must be [nNsS], defaulting to n\n");
not_already_printed = 0; /* so we don't get here again */
}
} /* scope of not_already_printed finishes here */
/* no break used here to fallback to the next case */
case 's': case 'S':
sortResultGreater = dog[y].weight > dog[y+1].weight;
break;
} /* switch */
if(sortResultGreater){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
I've created a program with pointers, the program works fine, however the bubble sort isn't functioning properly. Can someone assist me and show what I am doing wrong. In didn't have this problem with just arrays, but somehow it doesn't function well with pointers.
#include <stdio.h>
#include <ctype.h>
main()
{
// Initializing pointer arrays
int i;
int ctr = 0;
char ans;
char * movies[5] = {"John Wick 2", "Kong: Skull Island", "Justice League",
"Mummies", "Thor: Ragnarok"};
int movierate[5];
int outer, inner, didSwap, temprate;
char * tempmovies = "This will be used to sort rated movies";
printf("***Oscar Movie Rating***\n");
printf("Time to rate this years best picture.\n");
for(i = 0; i < 5; i++)
{
printf("\nHave you seen %s?", movies[i]);
scanf(" %c", &ans);
if((toupper(ans)) == 'Y')
{
printf("Please rate the movie on a scale from 1-10. ");
scanf(" %d", &movierate[i]);
ctr++;
continue;
}
else
{
movierate[i] = -1;
}
}
for(outer = 0; outer < 4; outer++)
{
didSwap = 0;
for(inner = outer; inner < 5; inner++)
{
if(movierate[inner] > movierate[outer])
{
tempmovies = movies[inner];
temprate = movierate[inner];
movies[inner] = movies[outer];
movierate[inner] = movierate[outer];
movies[outer] = tempmovies;
movierate[outer] = temprate;
didSwap = 1;
}
}
if(didSwap == 0);
{
break;
}
}
for(i = 0; i < ctr; i++)
{
printf("\n%s rated a %d!", movies[i], movierate[i]);
}
return (0);
}
Your problem is this code:
if(didSwap == 0);
{
break;
}
Consider sorting these numbers: 10 1 2 3 4
Since 10 is the highest number, there will not be any swap in the first outer-loop. Consequently you break out of the outer-loop and leaves the rest of the numbers unsorted.
So just try to remove the above code.
My program takes 3 lines of input. The first line being whether you want to sort it by odd or even, the second line being how large your array is and the third line being the integers in the array. It works until you use an array larger than 8. I believe it's to do with malloc but I've tried to debug this code for a couple of hours now and I can't fix this issue.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* sort;
int n;
int* ar;
int i;
int test()
{
int temp;
int j = 1;
//printf("%s", sort);
if (strcmp(sort, "odd") == 0) {
for (i = 0; i < n;) {
if (j != n) {
if (ar[i] % 2 != 0) {
if (ar[j] % 2 != 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
if (strcmp(sort, "even") == 0) {
for (i = 0; i < n; i++) {
if (j != n) {
if (ar[i] % 2 == 0) {
if (ar[j] % 2 == 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
}
void main()
{
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
//printf("%s", sort);
printf("Enter the elements of the array \n");
for (i = 0; i < n; i++) {
scanf("%d", &ar[i]);
}
test();
for (i = 0; i < n; i++) {
printf("%d ", ar[i]);
}
// return 0;
}
Code is typically executed in a linear fashion, but you don't seem to be doing that. You're allocating ar using n, but don't have a value for n yet until several lines later...
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
You're also not allocating the size of sort big enough to contain any string longer than 1 character.
This is my C Programming assignment. We're required to build a simple game that uses array. Our game is like the popular minesweeper game. At first, we initialise the 20*50 array area. Then we put some bombs randomly in the map. In the game, the player is required to travel from the starting point to the ending point to win the game. When the player moves, the movement will make the arrays hidden so that the user knows where did he start. However, in my case, the system doesn't update and make the array empty after the player moves. Can anyone help me with my 's' code? What is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define iMAX 20
#define jMAX 50
char array[20][50];
int i; //row
int j; //column
int z; //bomb
int n; //steps counter
int o; //x
int p; //y
o = 0;
p = 0;
int level;
int bomb;
char move;
int steps;
int main() {
printf("Welcome to the BombArray Game!\n");
printf("\nLevel 1 Begineer : 50 bombs\nLevel 2 Intermediate : 100 bombs\nLevel 3 Advance : 200 bombs\n");
printf("\nI want to challenge level ");
scanf_s("%d", &level);
printf("\n");
srand(time(NULL));
for (i = 0; i < 20; i++) {
for (j = 0; j < 50; j++) {
array[i][j] = '*';
}
}
array[0][0] = 'S';
array[19][49] = 'E';
if (level == 1) {
bomb = 50;
}
else if (level == 2) {
bomb = 100;
}
else if (level == 3) {
bomb = 200;
}
for (z = 0; z < bomb; z++) {
i = rand() % 20;
j = rand() % 50;
array[i][j] = '1';
}
do {
system("cls");
for (i = 0; i < iMAX; i++) {
for (j = 0; j < jMAX; j++) {
if (array[i][j] == 'S') {
printf("S");
}
else if (array[i][j] == '*') {
printf("*");
}
else if (array[i][j] == '1') {
printf("*");
}
else if (array[i][j] == 'E') {
printf("E");
}
else if (array[i][j] == '2') {
printf(" ");
}
}
printf("\n");
}
printf("\n\nMoving direction (w:up s:down a:left d:right e:exit): ");
scanf_s(" %c", &move);
printf("Steps? ");
scanf_s("%d", &steps);
if (move == 's') {
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
}
} while (array[19][49] != 2);
return 0;
}
if (move == 's') {
array[o][p] = '2';
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
array[o][p] = 'S';
}
You have to delete the S at the Start position and write it at the end position when you move
Some additional things: You don't need that much variables. You can remove i and j (or o and p).
If you enter something others than 1-3 for the level you will have an undefined number of bombs (if you declare the bomb variable as a local variable), therefore you should make a default case.
You never look if you are hitting a bomb, you just overwrite array[i][j] without prove if there's a bomb.
better:
if (move == 's') {
array[i][j] = '2';
for (n = 0; n < steps; n++) {
i++;
if (array[i][j] == '1') {
printf("bomb\n");
return 0;
}
array[i][j] = '2';
}
array[i][j] = 'S';
}