How to use integer 2D in C language? - c

I'm doing my college's task. I wrote like this
int debut[10][100];
char ngroup[10][100];
do
{
printf("1. Group name [1..25] : ");
gets (ngroup[0]);
}while (strlen(ngroup[0])< 1 || strlen(ngroup[0])>25);
do
{
printf("2. Year debute [1900-2011] : ");
scanf("%d",&debut[0]);
} while (debut[0] < 1900 || debut[0] > 2011);
I mean, I want to save a lot of group name which can be added by users, and also the year debut. But, when I made the validation of the year debut from 1900 until 2011 it's not work. Does anyone know the solution?

debut[0] is a pointer to array of 100 ints, and you try to compare it with an integer value.
You need something like this:
int debut[10];
...
scanf("%d",&debut[0]);
} while (debut[0] < 1900 || debut[0] > 2011);

Related

C: Initialize variable to random # b/w 50 & 100 so they can be used in Switch statement if user selects an option that doesn't include entering values

So i'm very much a beginner and this is an assignment for class, but i'm not looking to have someone do the assignment for me or anything. Just help on a part i'm having trouble with.
I'm not posting my code as it's an ongoing assignment and I don't want someone to happen upon it and copy it ): But the gist of it is I need to display a menu to the user and create a switch statement. Each case has a corresponding function prototype that executes the choice the user made from the menu.
1 Enter 3 grades
2 Show average (with 3 grades) and letter grade
3 Show highest grade
4 Show lowest grade
5 Exit
I've done pretty much all of the assignment, but the one requirement I can't figure out is how to initialize the 3 grade variables to random numbers between 50 and 100, so if the user chooses menu options 2 3 or 4 first then those random #'s are what is used in my prototypes. But if the user chooses menu option 1, my functions should use the 3 values input by the user from that point until exit, or if they hit 1 again to input new values.
Since I couldnt figure it out I just had each prototype prompt the user to insert 3 grades then proceed to do its assigned task using those values.
We were also instructed to not use arrays as we havent gotten to that yet.
If no one is able to figure it out without seeing the code i'll wait until after the due date and post what I was able to do. i'm honestly just wanting to learn and my professor doesn't really post any videos or lectures (online class) so we just go off our textbook and good ol google.
Thank you to whoever can help(:
If you want a variable with a random standard value, initialize it with a random value. You can generate a random integer between two numbers using the random() function in the stdlib.h header.
Your code can be structured like this.
#include<stdlib.h>
#include<time.h>
int random_range(int start, int end) {
return start + (int) ((double) random() / RAND_MAX * (end - start));
}
int main() {
srandom(time());
int grade1 = random_range(50, 100);
int grade2 = random_range(50, 100);
int grade3 = random_range(50, 100);
...
}
Now the three grade variables are always initialized and can be used. I recommend, you also read the man page for the random() function.
Not a good idea, doing processing with some randomly assigned data simply to not do the work of controlling the user's options. Imagine that one option is to write the current record into persistent storage. Do you want to risk random valued records polluting the company's database? There are stories of "test versions" that have been released "into the wild" (on the day the coder was home with a cold, but management applied pressure to ship) that... well, that would curl your toes.
Here is a sketch whereby the user has two options only: enter the data or quit the program. Presuming valid data has been accepted, the menu features more options.
Do not process junk. It'll come back to bite you.
/* Usual header files */
int main() {
char buf[ 64 ];
int hiMenuOpt = 1;
do {
printf(
"Here's menu options\n"
"0: Quit\n"
"1: Enter data\n"
);
if( hiMenuOpt > 1 )
printf(
"2: Something\n"
"3: Something else\n"
"4: Something other\n"
);
printf( "Select 0-%d : ", hiMenuOpt );
fgets( buf, sizeof buf, stdin );
int val = strtol( buf, NULL, 10 ); // Edit fix. Thanks to Lundin
if( val < 0 || hiMenuOpt < val ) {
printf( "Bad entry\n" );
continue;
}
switch( val ) {
case 0:
hiMenuOpt = 0;
break;
case 1:
puts( "Hi from one\n" );
/* yadda yadda */
hiMenuOpt = 4;
break;
/* More stuff */
}
} while( hiMenuOpt );
return 0;
}
Here's menu options
0: Quit
1: Enter data
Select 0-1 : 1
Hi from one
Here's menu options
0: Quit
1: Enter data
2: Something
3: Something else
4: Something other
Select 0-4 :
Notice that Quit is now item 0. New menu items may be added, and old ones removed. The only constant is exiting the program. It makes sense, imo, to make that the first item on the list.

When checking the validity of date of birth separated by dashes, an error rises when entering characters, and i can't solve that issue

from the requirements of my final project is to validate the scanned date of birth in the following format (DD-MM-YYYY).
the date of birth is a struct formed of 3 integers, day, month and year. So, I scan it from the user as follow:
scanf("%d-%d-%d",&dob.day,&dob.month,&dob.year);
However, when I enter a character, of course it enters an infinite loop.
I tried to use the flushinput concept (as I've used it with other scanned integers). It prevents the infinite loop. However, when re-scanning (through a certain loop), it keeps showing the "INVALID EMAIL" message, even though the entered email is correct! I guess this arises due to the presence of the dashes in the input.
So, can anybody tell me what to do?
Here's the part of the code where the issue arises (without the flushinput function):
void dobCheck(DATE dob) ///validates date of birth and rescans it if wrong
{
while(1)
{
if (dob.year<1806 || dob.year>2021 || dob.month<1 || dob.month>12 || dob.day<1 || dob.day >31)
{
dobCheckAct(dob); continue;
}
if ((dob.year%4)==0 && dob.month ==2 && dob.day >29)
{
dobCheckAct(dob); continue;
}
if (dob.year%4)!=0 && dob.month ==2 && dob.day >28)
{
dobCheckAct(dob); continue;
}
if (dob.month == 4 ||dob.month == 6 || dob.month == 9 || dob.month == 11) && dob.day> 30)
{
dobCheckAct(dob); continue;
}
break;
}
}
void dobCheckAct(DATE dob) ///action taken in case of invalid date of birth
{
printf("\a\n**INVALID DATE OF BIRTH!\n");
scanf("%d-%d-%d",&dob.day,dob.month,dob.year);
}
Thanks in advance!!

Accepting an input of multiple formats

I'm trying to create a code that accepts a date, however I want to give the user the ability to enter the date as dd/mm/yyyy or dd-mm-yyyy. My code is below, I tried to use OR but it does not work
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main ()
{
int dayA, monthA, yearA,
printf("First date in format DD/MM/YYYY or DD-MM-YYYY: ");
scanf("%d/%d/%d" || "%d-%d-%d", &dayA, monthA, yearA);
Here is a simple way to do it. It inputs into a string, and then checks if one of the format methods works. It's always essential to check the return value from the scanf function family, to know if the conversion succeeded.
#include<stdio.h>
int main(void)
{
int dayA, monthA, yearA;
puts("Enter a date dd/mm/yyyy or dd-mm-yyyy");
char datestr[32];
if(fgets(datestr, sizeof datestr, stdin) != NULL) {
if(sscanf(datestr, "%d/%d/%d", &dayA, &monthA, &yearA) == 3 || // added missing &
sscanf(datestr, "%d-%d-%d", &dayA, &monthA, &yearA) == 3) {
printf("Date is day %d, month %d, year %d\n", dayA, monthA, yearA);
}
}
}
Here are two runs of the program:
Enter a date dd/mm/yyyy or dd-mm-yyyy
23/4/2020
Date is day 23, month 4, year 2020
Enter a date dd/mm/yyyy or dd-mm-yyyy
23-4-2020
Date is day 23, month 4, year 2020

How to printf the value of input by user multiple times

I'm doing my c assignment and I have faced some problems. One of it is that I can't printf the value that are retrieved from the user. The value retrieved is in for loop and for the output it only shows the latest value that are entered by user. For this project, I can't use array or function. Someone please help me :(
printf("\n\nPlease Enter the number of bookings that you would like to make : ");
scanf("%d" , &noOfBooking );
//for control structures
for(i=1; i<=noOfBooking; i++){
printf("\nBooking %d" , i);
printf("\nSelect Room Type Option: ");
scanf("%d" , &option);
printf("Number of days: ");
scanf("%d" , &days);
printf("Number of person staying in the room: ");
scanf("%d" , &noPerson);
//selection structures
if(option==1)
{
ratePerDay = 75.00;
countSB--;
}
else if(option==2)
{
ratePerDay = 80.00;
countQB--;
}
else if(option==3)
{
ratePerDay = 100.00;
countKB--;
}
else if(option==4)
{
ratePerDay = 150.00;
countFR--;
}
else
printf("You have entered invalid input");
printf("Your Payment Booking are as follows :");
printf("\nRoom Type Option %d", option);
}
The expected output should be like this: -
Please Enter the number of bookings that you would like to make : 2
Booking 1
Select Room Type Option: 1
Number of days : 2
Number of person staying in the room : 1
Total Cost : 150.00
Booking 2
Select Room Type Option: 4
Number of days : 1
Number of person staying in the room : 3
Total Cost : 150.00
Your Payment Booking are as follows :
Room Type Option 1 (Single Bed) Total Cost is RM 150.00
Room Type Option 4 (Family Room) Total Cost is RM 150.00
I was thinking about using structs and the switch/case statement to solve your problem as they are not arrays or functions and you could store all the required information and afterwards handle the if/else if statements. For example:
// structs
// arguments related to your code
struct Booking {
int option;
int days;
int noPersons;
int num_of_Booking;
};
// switch-case
switch(option){
case 1:
ratePerDay = 75.00;
countSB--;
break; // optional - to terminate the switch statement
case 2:
...
.
.
case x:
...
default: // it works like the last else if your code
printf("You have entered invalid input");
As Paul said please provide some additional information on what you are trying to achieve in order for me to be more specific.
I hope that this helps you.
You can put every value in the same variable, for example, you can put the number 9 between every value that entered by the user.
For example if the user entered the options (1,3,2,2,4,3), the option value can be save in this way: option -> 193929294939
and than you will know every value that the user has entered.

Why my c program only produce zero answer while using for loop?

I tried to use for loop calculate the number of books keyed in and sum up their total price, but at the end i only get zero price in C program. What is my problem ? How to solve it?
#include<stdio.h>
int main(void)
{
int booknum;
float bookfee,bookgst,nogst,totfee,newfee,newfee_nogst;
bookgst=0.0;
nogst=0.0;
int cnt;
char code;
printf("Key in total books purchased >> ");
scanf("%d",&booknum);
for(cnt=1;cnt<=booknum;cnt++)
{
printf("\n\n");
printf("Key in price of the book >> ");
scanf("%f",&bookfee);
printf("Key in type( S=standard gst,Z=zero gst) \n>> ");
scanf("%c",&code);
getchar();
if(code=='S')
{
newfee=bookfee+0.6;
}
else if(code=='Z')
{
newfee_nogst=bookfee;
}
bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;
printf("\n");
}
totfee=bookgst+nogst;
printf("Book purchased with GST : RM %.2f\n",bookgst);
printf("Book purchased without GST : RM %.2f\n",nogst);
printf("Total payment : RM %.2f\n",totfee);
return 0;
}
There are a few problems with this code, but you're almost there!
First code reading needs to eat the previous \n (see this), otherwise the code is neither Z not S (it's a newline), and that's why the fees are never added.
(Search also for "fgets vs scanf" to see how to use the safer fgets).
scanf(" %c",&code);
then these lines
bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;
add the newfee / newfee_nogst ; these variables are set to 0 before the loop, but at the next occurence, they're still set to the value of the previous occurrence, thus either set them to 0 at the beginning of the loop, or, add the value directly in the if (see below). And since we're here, print an error if the code is wrong (and maybe subtract one to cnt to do one more loop with a correct code, in this case).
Also, the GST calculation is probably wrong, 6% of x is 0.06 * x, and if you want GST added to the value that's x * 1.06
if(code=='S')
{
bookgst = bookgst + bookfee*1.06; // or bookgst += bookfee*1.06
}
else if(code=='Z')
{
nogst = nogst + bookfee; // or nogst += bookfee
}
else {
printf("Code not understood\n");
}

Resources