Why does it say 'expected declaration specifiers before 'main'' - c

first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}

By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}

int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.

Related

How can I call my array in one function to another function and display specific data from that array?

#include <stdio.h>
int main(void) {
int choice;
do {
choice = getUserChoice();
switch (choice) {
case 1:
gameResults();
break;
case 2:
printf("game results:\n ");
break;
case 3:
printf("selected choice is 3\n");
break;
case 4:
printf("selected choice is 4\n");
break;
case 5:
//this case is to keep the default from triggering when selecting 5.
break;
default:
printf("please select a valid number 1-5.\n");
system("pause");
}
} while (choice != 5);
}
int getUserChoice() {
int x = 0;
printf("[1]Enter game results.\n");
printf("[2]Current record (number of wins, losse, and ties)\n");
printf("[3]Display ALL results from all games won.\n");
printf("[4]Display ALL results ordered from low to high.\n");
printf("[5]Quit.\n");
scanf_s("%d", &x);
return x;
}//end getUserChoice
int gameResults() {
int gameInput[1][2];
//counter variables for loop.
int i, j;
for (i = 0; i < 1; i++) {
for (j = 0; j < 2; j++) {
printf("please enter a value for gameInput[%d][%d]: ", i, j);
scanf_s("%d", &gameInput[i][j]);
return gameInput[i][j];
}
}
}
void prinGameResults() {
gameResults();
int wins, ties, losses = 0;
if()
}
So essentially I'm working on this assignment that is asking me to create a 2D array, have the user select stuff from a menu, put in 2 values for 2 team scores (one being "your" team and the other one being the opponents) I've created the array and now I'm looking to display this array when the user calls the 2nd switch case, and display numbers of wins, ties, etc etc.. the only problem is I have no idea how to call this array into one function from another, perhaps I'm doing this the in a wrong way, is there some easier way of going about this array?
You'll want to define your array inside main so that it can be passed as an argument (alongside its dimensions) to each function.
#include <stdio.h>
#include <stdlib.h>
int getUserChoice(void);
void getGameResults(size_t n, size_t m, int res[n][m]);
void printGameResults(size_t n, size_t m, int res[n][m]);
#define ROWS 1
#define COLS 2
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(ROWS, COLS, results);
break;
case 2:
printGameResults(ROWS, COLS, results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}
And for compilers that don't support variable-length arrays, you must be more rigid in your approach. There are a few ways to do this, here is one example:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 1
#define COLS 2
int getUserChoice(void);
void getGameResults(int res[ROWS][COLS]);
void printGameResults(int res[ROWS][COLS]);
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(results);
break;
case 2:
printGameResults(results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}

Why is my rand() function not working properly

So I am writing a gambling program for my c programming class. Essential its a menu for a dog track and you have to place a wager, select a dog, and the program chooses a winner and tells you if you won (how much) or lost. I use the ran() function but a specific dog that I set to win 10% of the time wins more than any other dog (including one that should win 40% of the time).
/*Programmer: John S. Bolen*/
/*Date: 3/1/19*/
/* User Will Choose to gamble, View Results, Or Quit program.
There are 9 Dogs to Chose from with a set %chance to win and
a set Payout Rate */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define SIZE 1000
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH nothingFlush()
#define SIZE 1000
void nothingFlush() {
char nothing;
while (scanf("%c", &nothing) == NULL);
}
typedef struct {
char name[100];
float payout;
float winOdds;
} DOG;
//Prototype Functions
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine);
void displayMenu();
void getBet(float *bet);
char getChoice();
float getOdds();
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine);
main() {
char userChoice;
DOG dog[SIZE];
int counter = 0;
int countOne = 0, countTwo = 0, countThree = 0, countFour = 0,
countFive = 0, countSix = 0, countSeven = 0, countEight = 0,
countNine = 0;
int winners[SIZE] = { 0 };
float bet = 0;
do {
userChoice = getChoice();
switch (userChoice) {
case 'G': // Gamble
getBet(&bet);
pickDog(dog, &counter, winners, &bet, &countOne, &countTwo, &countThree,
&countFour, &countFive, &countSix, &countSeven, &countEight, &countNine);
break;
case 'R': //Results
displayAllRaces(dog, winners,counter, countOne, countTwo, countThree, countFour,
countFive, countSix, countSeven, countEight, countNine);
break;
case 'L': //Leave
printf("\n\tThank you for visiting the Dog Track\n");
break;
default:
printf("\n\tERROR! -- Enter A Valid Selection...\n");
break;
}//End Switch
PAUSE;
} while (userChoice != 'L');
}
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine) {
int i = 0;
CLS;
printf("\n\tRace Results: \n");
printf("\tDog\t\t\t\t\tNum of Wins\n");
if (counter > 0) {
printf("\t%s\t\t\t%i\n", dog[0].name, countOne);
printf("\t%s\t\t\t%i\n", dog[1].name, countTwo);
printf("\t%s\t\t%i\n", dog[2].name, countThree);
printf("\t%s\t\t%i\n", dog[3].name, countFour);
printf("\t%s\t\t%i\n", dog[4].name, countFive);
printf("\t%s\t\t%i\n", dog[5].name, countSix);
printf("\t%s\t\t%i\n", dog[6].name, countSeven);
printf("\t%s\t\t\t%i\n", dog[7].name, countEight);
printf("\t%s\t\t\t%i\n", dog[8].name, countNine);
}
else {
printf("\n\t\n");
}
}
void displayMenu(){
CLS;
printf("\n\t==================================================\n");
printf("\n\t== MAIN MENU ==\n");
printf("\n\t==================================================\n");
printf("\n\t[G]amble\n");
printf("\n\t[R]esults\n");
printf("\n\t[L]eave\n");
printf("\n\tEnter Your Selection: ");
}
void getBet(float *bet) {
float result = 0;
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
if(result < 1 || result > 1000){
printf("\n\tERROR-- Please enter a valid amount\n");
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
}
printf("\n\tThank you for placing your wager.\n\tGood luck!\n");
*bet = result;
PAUSE;
}
char getChoice() {
char result;
displayMenu();
scanf_s("%c", &result); FLUSH;
result = toupper(result);
return result;
}
float getOdds() {
float odds[9] = { 40, 10, 8, 6, 1, 4, 8, 10, 13 };
return odds[9];
}
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine) {
int i = 0;
int choice;
float betMoney = 0;
int winner = 0;
CLS;
printf("\n\tPick a dog from the list:");
strcpy(dog[0].name, "\n\t1.Gandalf the Great");
strcpy(dog[1].name, "\n\t2.Fenrir Greyback");
strcpy(dog[2].name, "\n\t3.Marley the Magnificent");
strcpy(dog[3].name, "\n\t4.Clifford the Big Red Dog");
strcpy(dog[4].name, "\n\t5.Petey the Little Rascal");
strcpy(dog[5].name, "\n\t6.Courage the Cowardly Dog");
strcpy(dog[6].name, "\n\t7.Old Yeller Before the Bullet");
strcpy(dog[7].name, "\n\t8.Pongo the Dalmatian");
strcpy(dog[8].name, "\n\t9.Nymeria Stark\n");
for (i = 0; i < 9; i++) {
printf("%s", dog[i].name);
}
printf("\n");
scanf_s("%i", &choice); FLUSH;
do {
if (choice < 1 || choice > 9) {
printf("\n\tPlease, try again...\n");
scanf_s("%i", &choice);
}
} while (choice < 1 || choice > 9);
betMoney = *bet;
winner = 1 + rand() % (100 - 1 + 1);
if (winner <= 40) {
winner = 1;
(*countOne)++;
}
else if (winner <= 50) {
winner = 2;
(*countTwo)++;
}
else if (winner <= 48) {
winner = 3;
(*countThree)++;
}
else if (winner <= 64) {
winner = 4;
(*countFour)++;
}
else if (winner <= 65) {
winner = 5;
(*countFive)++;
}
else if (winner <= 69) {
winner = 6;
(*countSix)++;
}
else if (winner <= 77) {
winner = 7;
(*countSeven)++;
}
else if (winner <= 87) {
winner = 8;
(*countEight)++;
}
else if (winner <= 100) {
winner = 9;
(*countNine)++;
}
winners[*counter] = winner;
(*counter)++;
if (choice == winner) {
printf("\n\tYou picked a WINNER!\n");
if (winner == 1) {
(*bet) = betMoney * 2;
printf("You win $%.2f\n", *bet);
}
if (winner == 2) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 3) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 4) {
(*bet) = betMoney * 15;
printf("You win $%.2f\n", *bet);
}
if (winner == 5) {
(*bet) = betMoney * 50;
printf("You win $%.2f\n", *bet);
}
if (winner == 6) {
(*bet) = betMoney * 20;
printf("You win $%.2f\n", *bet);
}
if (winner == 7) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 8) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 9) {
(*bet) = betMoney * 3;
printf("You win $%.2f\n", *bet);
}
}
else {
printf("\n\tYou picked a LOSER!\n");
(*bet) = (*bet) - betMoney;
}
}
I have included the entire code for my program here (so you can test it if you wish), but only need help in fixing my rand() function. As you can see I want to randomly chose a number between 1-100. If the number is <= 40 then its dog one 40% chance to win, if the number is <= 50 (meaning its <= 50 but >40)then dog 2 wins with a 10% chance to win. I have run the program numerous times and dog 2 always seems to have the most wins after I run it x amount of times. Any help or suggestions would be greatly appreciated!

RSA Encryption C code

I am having trouble doing my homework.
I am doing an RSA application which can encrypt and decrypt.
The problem is that after I Input things to encrypt the results are weird and I can't decrypt anything. This is because when I copied the results of encryption which are symbols, I got more weird stuffs.
I'm guessing it has something to do with my formula getting negative ASCIIs as results.
Below is what I tried, and, in order to understand what I meant by weird, just compile and try it out(I have some unused stuffs which I haven't removed yet):
Output:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define boolean int
#define true 1
#define false 0
//===================================================//
int p = 0;
int q = 0;
int n = 0;
int m = 0;
int divider = 2;
int tempdivider = 2;
int initial = 0;
int x = 0;
int y = 0;
char msg[100];
char alphabet[27];
//===================================================//
void cls();
void menu();
void init();
void reinit();
void inputencrypt();
//int encrypt(int num);
void encrypt();
char decrypt(char text[]);
int fpb(int num);
int d(int num);
int primecheck(int a);
boolean checkdigit(char text[]);
//===================================================//
int main() {
frontpage();
init();
menu();
getchar();
return 0;
}
//===================================================//
void cls() {
for (int i = 0;i < 25;i++) {
printf("\n");
}
}
//===================================================//
boolean checkdigit(char text[]) {
int len = strlen(text);
for (int i = 0;i < len;++i) {
if (text[i]<'0' || text[i]>'9') {
return false;
}
}
return true;
}
int primecheck(int a) {
if (a == 1) {
return false;
}
for (int i = 2;i < a;i++) {
if (a%i == 0) {
return false;
}
}
return true;
}
//===================================================//
void reinit() {
for (int i = 1;i < 27;i++) {
alphabet[i] = 'a' + i - 1;
}
p = 0;
q = 0;
n = 0;
m = 0;
divider = 2;
tempdivider = 2;
initial = 120;
x = 0;
y = 0;
}
void init() {
reinit();
do {
printf("p = ");
scanf("%d", &p);fflush(stdin);
if (!primecheck(p)) {
printf("must be prime number! \n");
}
} while (!primecheck(p));
do {
printf("q = ");
scanf("%d", &q);fflush(stdin);
if (!primecheck(q)) {
printf("must be prime number! \n");
}
} while (!primecheck(q));
n = p*q;
m = (p - 1)*(q - 1);
initial = m;
x = fpb(m);
y = d(m);
printf("n = %d\n", n);
printf("m = %d\n", m);
printf("e = %d\n", x);
printf("d = %d\n", y);
system("pause");
}
//===================================================//
void menu() {
char input[2];
int input1 = 0;
do {
do {
cls();
printf("main menu\n");
printf("================\n");
printf("1. encrypt\n");
printf("2. decrypt\n");
printf("3. exit\n");
printf(">> ");
scanf("%s", input);fflush(stdin);
if (checkdigit(input)) {
input1 = atoi(input);
}
} while (!checkdigit(input));
switch (input1) {
case 1:
int c;
char encrypted[100];
char word[100];
printf("input word to encrypt : ");
scanf(" %[^\n]", word);fflush(stdin);
for (int i = 0;i < strlen(word);i++) {
if (word[i] == ' ') {
encrypted[i] = ' ';
//i++;
}
else {
for (int j = 1;j < 27;j++) {
if (word[i] == alphabet[j]) {
c = 0;
c = pow(j, x);
c = c%n;
encrypted[i] = c;
break;
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", word[i]);
}
printf(" ]\n");
printf("\n\nEncrypted ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", encrypted[i]);
}
printf(" ]\n");
printf("\n\nEncrypted [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%c", encrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
case 2:
int temp[100];
char decrypted[100];
char wordx[100];
int h;
printf("input word to decrypt : ");
scanf(" %[^\n]", wordx);fflush(stdin);
for (int i = 0;i < strlen(wordx);i++) {
temp[i] = wordx[i];
//temp[i] -= 97;
//printf("%d ::: %c\n", temp[i], temp[i]);
}
for (int i = 0;i < strlen(wordx);i++) {
if (wordx[i] == ' ') {
decrypted[i] = ' ';
}
else {
h = 0;
h = pow(temp[i], y);
h = h%n;
decrypted[i] = h;
for (int j = 1;j < 27;j++) {
if (decrypted[i] == j) {
decrypted[i] = alphabet[j];
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", wordx[i]);
}
printf(" ]\n");
printf("\n\nDecrypted ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", decrypted[i]);
}
printf(" ]\n");
printf("\n\nDecrypted [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", decrypted[i]);
printf("%c", decrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
}
} while (input1 != 3);
}
//===================================================//
int fpb(int num) {
if (!primecheck(num)) {
if (num%divider == 0) {
num = num / divider;
divider = 2;
}
else {
divider++;
}
fpb(num);
}
else if (primecheck(num)) {
if (!primecheck(num + divider)) {
tempdivider++;
divider = tempdivider;
num = initial;
fpb(num);
}
else {
return num + divider;
}
}
}
int d(int num) {
for (int i = 1;i < num;i++) {
if ((x*i) % num == 1) {
return i;
}
}
}
You have a general comprehension problem. Your console is only able to represent 96 characters correctly (known as printable 7bit-ASCII characters, 0x20 to 0x7F), but a byte can hold 255 different values. Your encryption algorithm does not care about this limited range, it will encrypt any value in the range [0..255] into another value in the range [0..255]. So your ASCII input characters will most likely be encrypted into values that cannot be represented by your console correctly. Copy&Past will not work correctly for non-printable characters (like 0x0B, which is a tab).
But now you will wonder: Why does that work for e.g. E-Mails? Simply: Because those characters are converted into an ASCII representation. Please google a bit for Base64 encoding.
As an alternative, you can always stream your encrypted characters into a file and later read back from that. This way you will bypass the limitations of your console.
Btw: Please have a look at the documentation of printf() and you will know, why you get those negative values.
The encrypt option has these three statements consecutively
c = 0;
c = pow(j, x);
c = c%n;
and the last of those will leave c in the range 0..(n-1).
Apart from that, there is no else clause and int c; can remain uninitialised.
So all in all it is inevitable that when you print c values as characters you will get "weird" results.
As for negative values, char encrypted[100]; is probably signed char so any integer value in the range 128..255 assigned to that, although undefined behaviour, may possibly show up as a negative number because the signed char is promoted back to int when passed as format %d to printf.

MiniMax algorithm tic-tac-toe in C explanation

trying to learn about computer game players to familiarise myself with AI. I understand how minimax works in theory but cant get my head around how this code I found online works.
can someone explain the minimax fruction/computer move function (lines 38-78)to me.
credit: https://gist.github.com/MatthewSteel/3158579
thanks
char gridChar(int i) {
switch(i) {
case -1:
return 'X';
case 0:
return ' ';
case 1:
return 'O';
}
}
void draw(int b[9]) {
printf(" %c | %c | %c\n",gridChar(b[0]),gridChar(b[1]),gridChar(b[2]));
printf("---+---+---\n");
printf(" %c | %c | %c\n",gridChar(b[3]),gridChar(b[4]),gridChar(b[5]));
printf("---+---+---\n");
printf(" %c | %c | %c\n",gridChar(b[6]),gridChar(b[7]),gridChar(b[8]));
}
int win(const int board[9]) {
//determines if a player has won, returns 0 otherwise.
unsigned wins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
int i;
for(i = 0; i < 8; ++i) {
if(board[wins[i][0]] != 0 &&
board[wins[i][0]] == board[wins[i][1]] &&
board[wins[i][0]] == board[wins[i][2]])
return board[wins[i][2]];
}
return 0;
}
int minimax(int board[9], int player) {
//How is the position like for player (their turn) on board?
int winner = win(board);
if(winner != 0) return winner*player;
move = -1;
int score = -2;//Losing moves are preferred to no move
int i;
for(i = 0; i < 9; ++i) {//For all moves,
if(board[i] == 0) {//If legal,
board[i] = player;//Try the move
int thisScore = -minimax(board, player*-1);
if(thisScore > score) {
score = thisScore;
move = i;
}//Pick the one that's worst for the opponent
board[i] = 0;//Reset board after try
}
}
if(move == -1) return 0;
return score;
}
void computerMove(int board[9]) {
int move = -1;
int score = -2;
int i;
for(i = 0; i < 9; ++i) {
if(board[i] == 0) {
board[i] = 1;
int tempScore = -minimax(board, -1);
board[i] = 0;
if(tempScore > score) {
score = tempScore;
move = i;
}
}
}
//returns a score based on minimax tree at a given node.
board[move] = 1;
}
void playerMove(int board[9]) {
int move = 0;
do {
printf("\nInput move ([0..8]): ");
scanf("%d", &move);
printf("\n");
} while (move >= 9 || move < 0 && board[move] == 0);
board[move] = -1;
}
int main() {
int board[9] = {0,0,0,0,0,0,0,0,0};
//computer squares are 1, player squares are -1.
printf("Computer: O, You: X\nPlay (1)st or (2)nd? ");
int player=0;
scanf("%d",&player);
printf("\n");
unsigned turn;
for(turn = 0; turn < 9 && win(board) == 0; ++turn) {
if((turn+player) % 2 == 0)
computerMove(board);
else {
draw(board);
playerMove(board);
}
}
switch(win(board)) {
case 0:
printf("A draw. How droll.\n");
break;
case 1:
draw(board);
printf("You lose.\n");
break;
case -1:
printf("You win. Inconceivable!\n");
break;
}
}
Here is the essence of minimax:
int minimax(int board[9], int player) {
// ....
for(i = 0; i < 9; ++i) { //For all moves,
// ....
int thisScore = -minimax(board, player*-1);
}
}
Go through each possible move, and for each such possible move, turn the board around, pretend to be the other player (that's the player*-1 part), and try each possible move. thisScore is set to the negative return value from the recursive call to minimax, since good for the other player equals bad for ourselves.
computerMove just goes through all the possible moves, calls minimax for each such possible move, and uses the one with the best result.

Replacing elements in an array

I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}

Resources