Lottery Program Problems - c

I'm currently in progress of creating my second main C program. I've only just started to learn C and I've had a few problems, as well confusion on what to do next with this program.
The idea is to basically allow the user to enter in a desired amount of years, then the program simulates the lottery games played every week, depending on how many years they enter. Then inside the program, I want the two arrays to compare to each other and check for any numbers they both have at the same time. The lottery ticket on the user's end stays the same, which is set inside the array and of course, the random lottery numbers change every week.
The basics are done, I'm just having a few problems, as well as not knowing where to go in certain areas.
Problems:
"int weeks = year * 52" doesn't work, says the initializer element isn't constant.
When I return the get_lotto_draw, I just get a bunched up number, it's not seperated in anyway, so I'm not sure how to do that.
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", &name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw);
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}
Update:
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw(*randomPtr));
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}

Borrowing mostly from the comments, there are a few problems with your code.
int weeks = year * 52; results in an error because year hasn't been initialized. Change it to int weeks = 0;, and then put weeks = year * 52 at the beginning of your main function.
You don't need the start: label at the beginning of your program, unless for some reason you want to go back there using a goto, which is usually considered bad practice.
printf("%d", get_lotto_draw); prints the address of get_lotto_draw as a decimal ("%d"), you need to make it get_lotto_draw(args) to get the return value of get_lotto_draw.
system("PAUSE"), runs the command PAUSE on the shell. I don't know if this will pause the current program, but if you don't want the program to exit, a loop will do instead.
while (1) {}
Your implementation of get_lotto_draw doesn't do what you think it does. What you are doing now is just returning randomNums, what you want to do is generate a random number between 1 and 49. To do this you should first generate a random number, and mod it by 48 and add one. This will get you a random number between 1 and 49. srand(time(NULL)); int r = rand(); will generate a random number, and r %= 48; r += 1; will mod it by 48 and add one. You can then do this for each iteration of that for loop, and create an array with the values. The array that you will return will have to be malloc'd.
int get_lotto_draw() {
srand(time(NULL));
int* rv = malloc(sizeof(int) * 6);
for (int i = 0; i < 6; i++) {
rv[i] = (rand() % 48) + 1;
}
return rv;
}
Your find_matches function is also unimplemented. Simply iterating through the arrays to find matches should suffice.
int find_matches(int* a, int* b) {
int matches = 0;
for (int i = 0; i < 6; i++) {
if (a[i] == b[i]) {
matches++;
}
}
return matches;
}
Lastly, for your print_array function, you again just need to iterate through the list of lottery numbers, and print each one.
void print_array(int* arr) {
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("%d", arr[5]);
printf("\n"); // remove this if you don't want a newline at the end.
}

Related

Program stops working after entering the value for more than 6 users

I have a school project which asks me to write a code using struct and functions, regarding sales in Greek cities. You are prompted to enter the values of 'em. The program works just fine if I enter that there's 6 salesmen, but a number larger than that makes it stop after entering all the values.. An example would be:
Number of salesmen: 7
(
Enter the his id:
Enter his surname:
Enter the number of sales:
Enter the area code:
) x7 times.
Then, when you enter the last value, it would just stop. Not exit, not stop responding/crash, literally just stop, and you would be unable to type anything more, only option would be to exit.
Thing is, there's no error or warning in both the build messages and the log, which has me quite confused.
My guess is that the error is in the function "calcSales" but I wanted to post the whole code just in case you need more info on it.
Could you take a look at the code and tell me if you find anything wrong? Thank you.
#include <stdio.h>
#include "genlib.h"
#include <simpio.h>
#include <string.h>
#define N 20
#define M 4
struct{
int id;
char surname[16];
long sales;
int area;
} salesmen[N];
void info(int *count);
void calcSales(int *count);
int main(){
int count;
printf("Give me the number of salesmen:\n");
count=GetInteger();
info(&count);
calcSales(&count);
}
void info(int *count){
for (int i=0; i<*count; i++){
printf("\nInfo for salesman number %d:\n", i+1);
printf("\nGive me his id: ");
salesmen[i].id=GetInteger();
printf("\nGive me his surname: ");
gets(salesmen[i].surname);
printf("\nGive me the number of sales: ");
salesmen[i].sales=GetLong();
printf("\n 1=Thessaloniki, 2= Athens, 3= Volos, 4= Hrakleio \n");
printf("\nLastly, give me the number of his area: ");
salesmen[i].area=GetInteger();
if (salesmen[i].area>4){
printf("\nThe number you are trying to enter doesn't match to an area.\n");
break;
}
}
}
void calcSales(int *count){
long tSales[4];
for (int i=0; i<*count; i++){
tSales[i]=0;
}
for (int i=0; i<*count; i++){
if(salesmen[i].area==1){
tSales[0]+=salesmen[i].sales;
}
if(salesmen[i].area==2){
tSales[1]+=salesmen[i].sales;
}
if(salesmen[i].area==3){
tSales[2]+=salesmen[i].sales;
}
if(salesmen[i].area==4){
tSales[3]+=salesmen[i].sales;
}
}
for (int i=0; i<4; i++){
printf("\nSales for area number %d: %ld\n",i+1, tSales[i]);
}
}
Your guess is correct. The mistake in calcSales function.
Exactly, the following part:
long tSales[4];
for (int i=0; i<*count; i++) {
tSales[i]=0;
}
The *count has value of 20. Which means the loop goes from i = 0 until i = 19.
When you access tSales[i] for i = 4 and above. You're invoking an undefined behavior. It's a memory that you didn't reserve for tSales. I suggest using the following:
long tSales[4];
for (int i=0; i<4; i++) {
tSales[i]=0;
}
Or better:
long tSales[4];
for (int i=0; i<sizeof(tSales)/sizeof(tSales[0]); i++) { // number of elements is the total size of array divided by the size of one element.
tSales[i]=0;
}
Or even better, you don't need a loop at all:
long tSales[4] = {0};
Besides your problem:
For the code you're providing, you don't need to pass a pointer to the functions.
You can make the code look as follows:
#include <stdio.h>
#include "genlib.h"
#include <simpio.h>
#include <string.h>
#define N 20
#define M 4
struct{
int id;
char surname[16];
long sales;
int area;
} salesmen[N];
void info(int count);
void calcSales(int count);
int main(){
printf("Give me the number of salesmen:\n");
int count=GetInteger(); // I've made declaration and assignment in same line. That seems cleaner to me.
info(count);
calcSales(count);
}
void info(int count){
for (int i=0; i<count; i++){
printf("\nInfo for salesman number %d:\n", i+1);
printf("\nGive me his id: ");
salesmen[i].id=GetInteger();
printf("\nGive me his surname: ");
gets(salesmen[i].surname);
printf("\nGive me the number of sales: ");
salesmen[i].sales=GetLong();
printf("\n 1=Thessaloniki, 2= Athens, 3= Volos, 4= Hrakleio \n");
printf("\nLastly, give me the number of his area: ");
salesmen[i].area=GetInteger();
if (salesmen[i].area>4 || salesmen[i].area < 1){ // Added an extra condition.
printf("\nThe number you are trying to enter doesn't match to an area.\n");
break;
}
}
}
void calcSales(int count){
long tSales[4] = {0};
for (int i=0; i<count; i++){
tSales[salesmen[i].area - 1]+=salesmen[i].sales; // No need for if conditions.
}
for (int i=0; i<4; i++){
printf("\nSales for area number %d: %ld\n",i+1, tSales[i]);
}
}

Having problems with 2D char arrays

So I've got an assignment where my program asks the brand (10 letters), model (10 letters), age (1986 - 2019) and cost (positive real number) of 10 cars and then wants the program to check which car is the oldest and to print out it's brand and model. I don't have a problem with the first part but with the second part.
The code is:
//First part
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C 10
#define M 11
int main(void)
{
char brand[C][M];
char model[C][M];
int year[C];
float cost[C];
int i, len1, len2, min;
for(i=0; i<C; i++){
printf("Car %d\n", i+1);
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
do{
printf("Model: ");
scanf("%s", model[i]);
len2 = strlen(model[i]);
} while(len2<0 || len2>10);
do{
printf("Year: ");
scanf("%d", &year[i]);
} while(year[i]<1986 || year[i]>2019);
do{
printf("Cost: ");
scanf("%d", &cost[i]);
} while(cost[i]<=0);
}
//Second part
year[0] = min;
for(i=0; i<10; i++)
if(year[i] < min){
min = year[i];
printf("\nThe oldest car is %s %s\n", brand[i], model[i]);
}
For some reason it either prints out gibberish in the place of brand[i] or if I lose the columns of the if statement prints out all the car brands and their models, where I only want the oldest one.
Aside from scanf not being recommended there are some problems with this code, first when you read the brand and model you do:
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
The problem here is that you first write the string to brand[i] and then check if it's too long, but you have already written it into the array so if the string is longer than your space you already have a buffer overflow. Limit the size you can read with scanf using scanf("%10s, brand[i]) or better yet use fgets(brand[i], sizeof(brand[i]), stdin).
Next in the second part you use min without initializing it, and you overwrite the content of year[0] with it. You probably wanted something like:
min = 2020; // or a number that will be bigger than all your cars anyway
int older = 0;
i = 0;
for(i=0; i<C; i++){ // Use C here, you have it might as well use it instead of magic numbers
if(year[i] < min){
older = i;
min = year[i];
}
}
printf("\nThe oldest car is %s %s\n", brand[older], model[older]);
but bare in mind that this solution will print multiple cars if they are the oldest ones and have the same year

Issue with getting user input into a Dynamic array C

I seem to be having trouble getting user input into a dynamic array in C.
#include "stdio.h"
int main(void){
int counter = 0;
int x = 1;
int i;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i);
char teams[i];
for (counter = 0; counter < i; counter++){
char teams[counter];
printf("Enter team names: \n");
scanf("%s", teams);
}
for (counter = 0; counter < i; counter++){
char teams[counter][10];
printf(" Team %d is %s \n", x, *teams);
x++;
}
}
When I run this code I get a the following output,
Enter the number of teams playing in the league: 2
Enter team names: Team1
Enter team names: Team2
Team 1 is Team1
Team 2 is \320\365\277\357\376
Program ended with exit code: 0
Not able to figure out my mistake. Would love any and all help.
Thank You!
There are some basic mistakes, especially with your understanding of pointers and C language concepts. "team" is an array of char pointers, and char teams[i] isn't quite correct; one correct way is to dynamically allocate memory for the collection of team names. By comparing the code below to yours, I am sure you can spot the areas where you made mistakes. PS: I am using the format character "m" inside scanf to dynamically allocate memory for the team name.
int main(int argc, char **argv){
int counter = 0;
int i, ret;
char **teams;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i); // check return value yourself
teams=(char **)malloc(sizeof(char *)*i);
if(NULL==teams) perror("not enough memory"), exit(1);
for (counter = 0; counter < i; counter++){
printf("Enter team names: \n");
ret=scanf("%ms", &teams[counter]);
if(ret<1)//hanndle error. i'll just quit.
exit(-1);
}
for (counter = 0; counter < i; counter++){
printf(" Team %d is %s \n", counter+1, teams[counter]);
free(teams[counter]);
}
free(teams);
}

Check for Character instead of Integer [duplicate]

This question already has answers here:
Check if a value from scanf is a number?
(2 answers)
Closed 9 years ago.
my program adds numbers entered by the user. It runs and works great until a character is entered instead of an integer. Is there a simple way to make sure only integers are entered from the keyboard?
Here is my code.
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
scanf("%d",&TotalOfNumbers);
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
You need to check the return value of scanf. If the input was a valid number, it will return 1. If the input was not a valid number, it will return something else. Here is your code modified to put the checks in.
#include<stdio.h>
#include <stdlib.h>
int get_number()
{
int num;
int ret;
ret = scanf("%d", &num);
if (ret != 1) {
printf("bad number\n");
exit(EXIT_FAILURE);
}
return num;
}
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
n = get_number();
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
TotalOfNumbers = get_number();
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
Check the ferror state on the input stream
scanf("%d",&TotalOfNumbers);
if(!ferror(stdin)){
sum = sum + TotalOfNumbers;
}
In addition to posted answer, there options not general as posted, but quicker.
First if you want to skip some final set of characters.In following example all letters,! and + will be skiped
int n;
scanf("%*[a-zA-Z!+]%d",&n);
printf("\n%d",n);
for input
weweqewqQQWWW!!!!+++3332
the output is
3332
Next option is to use buffer wich allowed to read everything untill number is met, and then read the number. The disadvantage is that buffer size is limited
char buf[25];
int n;
scanf("%[^0-9]%d",buf,&n);
printf("\n%d",n);
For input
fgfuf#$#^^#^##4565
Output
4565

Expression must have class type error

I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.

Resources