Can't get my C program to print the output - c

When I go to print the output of the program everything shows up as zero. I think the variable aren't storing themselves, but I'm not totally sure. When I go to look over everything, it looks right but clearly isn't. Any help would be really appreciated. Sorry if the formatting seems a little off, Stack Overflow wouldn't accept it otherwise.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
}
i++;
return val;
}
void error()
{
printf("Error: Sales figures must be numbers.\n");
printf("Please try again.\n");
}
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if( isdigit(term[i]) == 0)
{
return false;
i++;
}
}
return true;
}
int main()
{
int sales[3][2], costs[3] = {3, 4, 1}, weekends[2] = {0, 0};
int i, j, val;
char term[100];
while (1)
{
printf("Number of Bagel sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[0][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[1][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Saturday: ");
scanf("%s", term);
if (isnumber(term) == false)
{
error();
}
else
{
sales[2][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Bagel sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[0][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[1][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[2][1] = digit(term);
break;
}
}
for (i = 0; i < 2, i++;)
{
for (j = 0; j < 3, j++;)
{
weekends[i] += costs[j] * sales[i][j];
}
}
printf("\n");
for (i = 0; i < 3, i++;)
{
printf("%d", costs[i]);
}
printf(".");
for (i = 0; i < 3, i++;)
{
for (j = 0; j < 2, j++;)
{
printf("%d", sales[i][j]);
}
if (i == 0)
{
printf(" = ");
printf("%d %d", weekends[0], weekends[1]);
}
printf("\n ");
}
printf("\nTotal sales on Saturday: $%d", weekends[0]);
printf("\nTotal sales on Sunday: $%d", weekends[1]);
printf("\nTotal sales over the weekend: $%d", weekends[0] + weekends[1]);
return 0;
}

You are not incrementing i in the loop. Your code for digit is:
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
}
i++; /* ---- this is outside the loop !! */
return val;
}
But it ought to look like:
int
digit(const char *term)
{
int val = 0;
while( *term != '\0' ){
val = val * 10 + *term - '0';
term += 1;
}
return val;
}

Related

String input scanf for struct

This is the question consisting of 1st stage, 2nd stage and 3rd stage.
This is the code for 1st stage and it works well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char name[20];
char phoneNumber[15];
char birthDate[8];
};
struct PERSON record[100];
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount].name);
printf("Phone_number: ");
phoneNumValidation(record[personCount].phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount].birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i].name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j].name, record[j + 1].name);
strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
strcpy(record[j].birthDate, record[j + 1].birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i].birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
}
int main() {
int menuNum;
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:registration(); break;
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
And this is the code for 2nd stage where I modified according to the question but I encountered error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount].name);
printf("Phone_number: ");
phoneNumValidation(record[personCount].phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount].birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i].name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j].name, record[j + 1].name);
strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
strcpy(record[j].birthDate, record[j + 1].birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i].birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
}
int main() {
int menuNum;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < n)
{
registration(n);
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
I received error messages when compiling, so I follow the error messages where I need to change all the . to ->.
And it can be compiled and run.
I manage to input max_num and menuNum.
When I input menuNum 1 (void registration), I try to input the name, but the program stops immediately.
Where did I go wrong?
This is the code after I change all the . to ->
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount]->name);
printf("Phone_number: ");
phoneNumValidation(record[personCount]->phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount]->birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i]->name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j]->name, record[j + 1]->name);
strcpy(record[j]->phoneNumber, record[j + 1]->phoneNumber);
strcpy(record[j]->birthDate, record[j + 1]->birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i]->birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
}
int main() {
int menuNum, max_num;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < max_num)
{
registration();
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
Latest code I edit using suggestion by #itati.
I manage to input name, phone number and birthdate. But I can only input once even though I set the max_num to 3, and the program stops immediately after input birthdate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration(int max_num) {
record = (struct PERSON**) malloc(max_num* sizeof(struct PERSON**));
while (true){
printf("Name: ");
nameValidation(record[personCount]->name);
printf("Phone_number: ");
phoneNumValidation(record[personCount]->phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount]->birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
}
void showAll() {
for (int i = 0; i < personCount; i++) {
//printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
//if (strcmp(name, record[i].name) == 0) {
if (strcmp(name, record[i]->name) == 0) {
for (int j = i; j < personCount; j++) {
//strcpy(record[j].name, record[j + 1].name);
//strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
//strcpy(record[j].birthDate, record[j + 1].birthDate);
strcpy(record[j]->name, record[j + 1]->name);
strcpy(record[j]->phoneNumber, record[j + 1]->phoneNumber);
strcpy(record[j]->birthDate, record[j + 1]->birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
//getBirthMonth[check] = record[i].birthDate[position + check - 1];
getBirthMonth[check] = record[i]->birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
//printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
}
int main() {
int menuNum, max_num;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < max_num)
{
registration(max_num);
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
I don't know why you need to use flush and PERSON**.
According to the problem, maybe you wrote "loop" in the wrong place.
I rewrite a code, it should be ok.
void registration(int n)
{
record = (struct PERSON*) malloc(n* sizeof(struct PERSON*));
while (true){
printf("Name: ");
scanf("%s", record[personCount]->name);
printf("Phone Number: ");
scanf("%s", record[personCount]->phoneNumber);
personCount++;
printf("<<%d>>\n", personCount);
}
}

How to count the number of collisions in hash table?

Here's the task: "Develop a program for the formation and processing of hash tables, built on the principle of open addressing (private hashing). Practical evaluation of hash tables for the set structure, including the data key N-bit digital code (N >= 10). Explore two probing methods: linear and quadratic. Analyze and calculate the results obtained, first of all, the occurrence of collisons and the search time data for different indicators table coverage ratios"
???For some reason I can't do the last one. I can't count collisions and their output in any way, and calculate the search time. Suggest ideas for the algorithm, plz???
Here`s code:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN 20
typedef struct inform {
char* key, * name;
} INFO;
typedef struct hash_table {
int count, size;
INFO** array;
}HTAB;
INFO* New_Item(char* key, char* name)
{
INFO* result = (INFO*)malloc(sizeof(INFO));
result->key = key;
result->name = name;
return result;
}
void free_item(INFO* item)
{
if (item != NULL)
free(item);
}
HTAB* NewHTAB(int size)
{
HTAB* result = (HTAB*)malloc(sizeof(HTAB));
result->count = 0;
result->size = size;
result->array = (INFO**)malloc(sizeof(INFO*) * size);
memset(result->array, NULL, sizeof(INFO*) * size);
return result;
}
void free_hash_table(HTAB* table)
{
if (table != NULL) {
for (int i = 0; i < table->size; i++) {
INFO* item = table->array[i];
if (item != NULL) free_item(item);
}
free(table->array);
free(table);
}
}
int ht_hasItem(HTAB* table, int idx)
{
return table->array[idx] != NULL;
}
int ht_IsFull(HTAB* table)
{
return table->count == table->size;
}
int Hash_Code(int key, int size)
{
return key % size;
}
int Insert(HTAB* table, char* keycpy, char* namecpy)
{
int result = 0;
char* key = _strdup(keycpy);
char* name = _strdup(namecpy);
if (ht_IsFull(table)) printf("Hash table is FULL!!!");
else {
INFO* item = New_Item(key, name);
int idx = Hash_Code(atoi(key), table->size);
//int h = 1;
while (ht_hasItem(table, idx)) {
idx = Hash_Code(idx + 1, table->size);
}
//idx = Hash_Code(idx + (h*h), table->size);
//h++;
table->array[idx] = item;
table->count++;
}
return result;
free(key);
free(name);
}
void Display(HTAB* table)
{
printf("-------------------------------------------------\n");
for (int i = 0; i < table->size; i++) {
if (ht_hasItem(table, i)) {
INFO* item = table->array[i];
printf(" %d\t| %s\t| %s \t|\n", i, item->key, item->name);
printf("-------------------------------------------------\n");
}
else {
printf(" %d\t| ---\t| \t---\t\t|\n", i);
printf("-------------------------------------------------\n");
};
}
printf("\n");
}
int Search(HTAB* table, char* key)
{
int result = -1;
int idx = Hash_Code(atoi(key), table->size);
// int h = 1;
while (ht_hasItem(table, idx)) {
if (strcmp(table->array[idx]->key, key) == 0) {
result = idx;
break;
}
else idx = Hash_Code(idx + 1, table->size);
//idx = Hash_Code(idx + (h*h), table->size);
//h++;
}
return result;
}
INFO* Remove(HTAB* table, char* key)
{
INFO* result = NULL;
int idx = Search(table, key);
if (idx != -1) {
result = table->array[idx];
table->array[idx] = NULL;
table->count--;
}
return result;
}
int main() {
int itemIdx = 0;
INFO* item = NULL;
HTAB* table = NewHTAB(30);
char name[LEN], key[LEN];
int choice = 0, c;
system("chcp 1251");
FILE* ftxt;
if (!(ftxt = fopen("RGR_2_AP.txt", "r"))) {
puts("\n File not found...\n");
return 0;
}
while (fscanf(ftxt, "%s%s", name, key) == 2)
Insert(table, key, name);
printf("\n Іndex\t| Кey\t| \t NAME\t\t|\n");
Display(table);
do {
printf("MENU-: \n1.Insert new item"
"\n2.Search item"
"\n3.Delet item"
"\n\n Please choose one point-:");
scanf_s("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter name: ");
rewind(stdin);
gets_s(name);
printf("\nВведіть ключ: ");
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
Insert(table, key, name);
printf("\n");
Display(table);
break;
case 2:
printf("\nEnter key: ");
rewind(stdin);
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
itemIdx = Search(table, key);
if (itemIdx != -1) {
item = table->array[itemIdx];
printf("Item found: (%d, %s, %s)\n", itemIdx, item->key, item->name);
}
else printf("Item not found\n");
break;
case 3:
printf("\nEnter key: ");
rewind(stdin);
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
Remove(table, key);
Display(table);
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want continue(enter 1 if yes)?-:\t");
scanf_s("%d", &c);
} while (c == 1);
free_hash_table(table);
printf("End...\n");
return 0;
}
You could add variables which count collisions in the Insert and Search methods, as well as the run time. You may need to return a list in that case, with the first element being the index, second being the # of collisions, and third being the run time.
Use the chrono library to time your functions.

C program query

So this is my program and the number, name, address doesn't print again after single execution and also If the seat is already taken there should be "seat is taken already, please try again" which I'm confused about
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct passenger
{
char name[20];
char address[30];
int age;
};
struct passenger data;
struct rwcl
{
int row;
char col;
};
int clmn, i, j;
int arr[5][5];
struct rwcl number;
for(i=0;i<5;i++)
{
printf("Enter Your Name: ");
scanf("\n");
gets(data.name);
printf("Enter Your Address: ");
scanf("\n");
gets(data.address);
printf("Enter Your Age: ");
scanf("%d", &data.age);
printf("\nAll aboard! You may now choose your desired seat/s.");
while(i<5){
for(j=0;j<5;j++){
if (j == 0) {
arr[i][j] = i+1;
}
if(j == 1){
arr[i][j] = 'A';
}
if(j== 2){
arr[i][j] = 'B';
}
if(j == 3){
arr[i][j] = 'C';
}
if(j== 4){
arr[i][j] = 'D';
}
}
i++;
}
printrwcl:
printf("\n\n");
for(i=0;i<5;i++){
for(j=0;j<5;++j){
if(j == 0 ){
printf("%-5d", arr[i][j]);
}
else {
printf("%-5c", arr[i][j]);
}
}
if(j==5) {
printf("\n");
}
}
printf("\n");
rowselect:
printf("Choose a row between 1,2,3,4,5 or 6 for cancellation: ");
scanf("%d", &number.row);
if(number.row < 0 || number.row > 6) {
printf("\nPlease, re-enter. Thank you.\n");
goto rowselect;
}
if(number.row == 6) {
printf("Recorded, thank you.");
exit(0);
}
columnselect:
printf("Choose a letter between A,B,C,D: ");
scanf("\n");
scanf("%c", &number.col);
switch(number.col)
{
case 'A':
clmn = 1;
break;
case 'B':
clmn = 2;
break;
case 'C':
clmn = 3;
break;
case 'D':
clmn = 4;
break;
}
if(arr[number.row-1][clmn] == 'X')
{
printf("Seat is taken. Please choose a different one.");
}
else
{
printf("Seat %d%c has been reserved.", number.row, number.col);
arr[number.row-1][clmn] = 'X';
}
goto printrwcl;
}
}

C program only running the first loop and then stopping

Every time I try and run only the first loop runs. It ask how many items were sold and then just stops running. I'm not really sure what I did wrong. If anyone has any tips that would be great(story if there's some formatting issues, SO wouldn't let me post the question without them).
Everything else looks fine but if any other improvements could be made please let me know.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
i++;
}
return val;
}
void error()
{
printf("Error: Sales figures must be numbers.\n");
printf("Please try again.\n");
}
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if( isdigit(term[i]) == 0)
{
return false;
i++;
}
}
return true;
}
int main()
{
int sales[3][2], costs[3] = {3, 4, 1}, weekends[2] = {0, 0};
int i, j, val;
char term[100];
while (1)
{
printf("Number of Bagel sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[0][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[1][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Saturday: ");
scanf("%s", term);
if (isnumber(term) == false)
{
error;
}
else
{
sales[2][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Bagel sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[0][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[1][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[2][1] = digit(term);
break;
}
}
for (i = 0; i < 2, i++;)
{
for (j = 0; j < 3, j++;)
{
weekends[i] += costs[j] * sales[i][j];
}
}
printf("\n");
for (i = 0; i < 3, i++;)
{
printf("%d", costs[i]);
}
printf(".");
for (i = 0; i < 3, i++;)
{
for (j = 0; j < 2, j++;)
{
printf("%d", sales[i][j]);
}
if (i == 0)
{
printf(" = ");
printf("%d %d", weekends[0], weekends[1]);
}
printf("\n ");
}
printf("\nTotal sales on Saturday: $%d", weekends[0]);
printf("\nTotal sales on Sunday: $%d", weekends[1]);
printf("\nTotal sales over the weekend: $%d", weekends[0] + weekends[1]);
return 0;
}
You have an infinite loop in isnumber(). It will return false if the first character is not a digit. But if the first character is a digit, it never increments i, so it keeps testing the first character repeatedly.
i++ should not be in the if statement.
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if(!isdigit(term[i]))
{
return false;
}
i++;
}
return true;
}
And as others have pointed out, you need to put () after error to call it.
As for your programming stopping; you use isdigit on line 30 without declaring it.
Along that, you use error everywhere without invoking it. Use error() to invoke the function and print the error-information.
Just a small formatting tip as well: instead of if (something == false) use if (!something)
Your use of error; is incorrect. You should write error(); instead.

Loop incomplete

I just started learning coding for about 2 months because of the course im taking.
My code works (kinda) but after the 1st loop it wont show the 1st line of the main function("You have been given 20 pokeballs, embrak on you quest on becoming a Pokeman Master!!!:), and i dont know why!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int pokeball = 20;
int rand_num;
int PokemonCaught[5] = { 0, 0, 0 ,0, 0 };
int poke_captured = 0;
int rungame = 1;
int stopgame = 1;
int total;
int randomnum();
int encounter_rate();
int pokemon_met();
void BallThrow();
void CaughtPokemon();
void checkball();
void PokeSummary();
char exitno();
int clear();
int main()
{
printf("You have been given 20 pokeballs, embrak on you quest on becoming a Pokeman Master!!!\n");
getchar();
do
{
checkball();
encounter_rate();
pokemon_met();
} while (stopgame == 0);
PokeSummary();
return 0;
}
int randomnum()
{
srand(time(NULL));
}
int encounter_rate()
{
randomnum();
rand_num = rand() % 100;
}
int pokemon_met()
{
if (rand_num <= 30)
{
printf("A wild Margikarp appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 50)
{
printf("A wild Charmander appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 70)
{
printf("A wild Jigglypuff appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 85)
{
printf("A wild Pikachu appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else
{
printf("A wild Dragonite appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
}
void checkball()
{
if (pokeball > 0)
{
stopgame = 0;
}
else
{
stopgame = 1;
}
}
void BallThrow()
{
randomnum();
int BallChance;
int PokeRun;
BallChance = rand() % 2;
pokeball = pokeball - 1;
if (BallChance == 1)
{
printf("Gotcha!\n");
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to continue your journey!\n\n");
poke_captured = poke_captured + 1;
CaughtPokemon();
getchar();
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
}
else if (BallChance == 0)
{
PokeRun = rand() % 2;
printf("The pokemon broke free!!!\n");
if (PokeRun == 0)
{
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
else
{
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to throw pokeball!\n\n");
getchar();
BallThrow();
}
}
else if (PokeRun == 1)
{
printf("Oh no! The pokemon ran away!\n");
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to continue your journey!\n\n");
getchar();
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
}
}
}
void CaughtPokemon()
{
if (rand_num <= 30)
{
PokemonCaught[0] = PokemonCaught[0] + 1;
}
else if (rand_num <= 50)
{
PokemonCaught[1] = PokemonCaught[1] + 1;
}
else if (rand_num <= 70)
{
PokemonCaught[2] = PokemonCaught[2] + 1;
}
else if (rand_num <= 85)
{
PokemonCaught[3] = PokemonCaught[3] + 1;
}
else if (rand_num <= 95)
{
PokemonCaught[4] = PokemonCaught[4] + 1;
}
}
void PokeSummary()
{
int point0, point1, point2, point3, point4, total;
point0 = (PokemonCaught[0]) * 10;
point1 = (PokemonCaught[1]) * 30;
point2 = (PokemonCaught[2]) * 30;
point3 = (PokemonCaught[3]) * 50;
point4 = (PokemonCaught[4]) * 70;
total = point0 + point1 + point2 + point3 + point4;
printf("You have successfully caught %d Pokemon!\n\n", poke_captured);
printf("You have caught:\n");
printf("Margikarp = %d (%dpoints)\n", PokemonCaught[0], point0);
printf("Charmander = %d (%dpoints)\n", PokemonCaught[1], point1);
printf("Jigglypuff = %d (%dpoints)\n", PokemonCaught[2], point2);
printf("Pikachu = %d (%dpoints)\n", PokemonCaught[3], point3);
printf("Dragonite = %d (%dpoints)\n", PokemonCaught[4], point4);
printf("\nTotal points = %d\n", total);
exitno();
}
char exitno()
{
char stay;
printf("Press 'y' to continue, press any other key to quit.");
scanf(" %c", &stay);
if (stay == 'y' || stay == 'Y')
{
clear();
return (main);
}
else
{
printf("Thank you for playing!!");
exit(0);
}
}
int clear()
{
total = total * 0;
poke_captured = poke_captured * 0;
PokemonCaught[0] = PokemonCaught[0] * 0;
PokemonCaught[1] = PokemonCaught[1] * 0;
PokemonCaught[2] = PokemonCaught[2] * 0;
PokemonCaught[3] = PokemonCaught[3] * 0;
PokemonCaught[4] = PokemonCaught[4] * 0;
pokeball = pokeball + 20;
}
I appreciate any help and i know my codes are far from being decent (sigh)
. Thanks
You have made an error when calling main in char exitno() function:
char exitno()
{
char stay;
printf("Press 'y' to continue, press any other key to quit.");
scanf(" %c", &stay);
if (stay == 'y' || stay == 'Y')
{
clear();
return ((char)main()); // main it should be called using parenthesis
}
else
{
printf("Thank you for playing!!");
exit(0);
}
}
That is not inside of your do-while loop.
If you want it to execute every time, then just move it down into the the loop. Otherwise, your program will move past in the first few milliseconds of operation. Alternatively, modify it (likely, put it within a new function) to print out some information that might change during execution of your program--say, the current number of pokeballs remaining.

Resources