GPA scores program - c

I am supposed to write a program where the user is asked how many students there are in a class. Then, it asks for the GPA of each of those students. In the end, it is supposed to display number of students with each GPA score. So far this is what i have, but it doesn't seem to count properly.
#include <stdio.h>
int main(void){
int cnt1, cnt2, cnt3, cnt4, student, numofsdts, GPA, GPAFreq[4];
printf("Enter number of students: ");
scanf("%d", &numofsdts);
student = 1;
while(student <= numofsdts){
printf("GPA of student number %d: ", student);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
}
else{
student++;
}
if(student == numofsdts + 1)
break;
if(GPAFreq[1])
cnt1++;
else if(GPAFreq[2])
cnt2++;
else if(GPAFreq[3])
cnt3++;
else if(GPAFreq[4])
cnt4++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}

Set int cnt1 = 0, cnt2 = 0 etc. (they are not nullified by default, just have some garbage [like a rented room not cleaned explicitly...]).
Also:
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue; // skip the rest of the loop body
}
Or a slightly cleaner approach (in full):
#include <stdio.h>
int main(void){
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
int numofsdts, GPA;
printf("Enter number of students: ");
scanf("%d", &numofsdts);
students = 0;
while(students <= numofsdts){
printf("GPA of student number %d: ", students + 1);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue;
}
if(GPA == 1)
cnt1++;
else if(GPA == 2)
cnt2++;
else if(GPA == 3)
cnt3++;
else if(GPA == 4)
cnt4++;
students++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}

There are multiple errors here. The first is that cnt1-4 have to be initialized prior to being added to. The second is that C uses zero indexing, so GPAFreq[4] is not accessing the fourth element of your array (which would be GPAFreq[3].
The third is that your if statement isn't doing what you think it is. It is evaluating the values inside of your array as boolean variables, i.e. 0 is false, anything else is true. A better approach is to do this:
GPAFreq[GPA - 1] += 1;
This will be counting the frequencies in each of the indices of the array. Then to print them, you just access GPAFreq and no longer need the cnt variables.

Related

C Programming - Getting the Median from User Inputs

I need help fixing my code. What my code does it asking users to input a number multiple times and will terminate the program once -1 is entered. Then, will get the Sum, Max, Min, Average and Median values.
Sum, Min and Max seems to be working fine. But on the "Average" it's treating the -1 as a userinput, also, I need help on how to get the median value.
Here's what I got so far.
#include <stdio.h>
int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;
printf("Please enter your name: ");
scanf("%s", &name);
printf("Hello, %s, ", name);
do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if (userInput == -1) break; // I added this line, average works fine now
sum = sum + userInput;
count = count + 1;
average = sum / count;
if (userInput > max){
max = userInput;
}
if (userInput < min && userInput >= 0){
min = userInput;
}
}
while (userInput >= 0);
printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);
return 0;
}
Here's my sample output:
Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10
So The rest seems to be working now after some modification except for getting the median value.
You do not want to increment the count when userInput == -1
You're incrementing the count and adding to the sum before checking whether userInput == -1. Try rewriting your loop:
while(1){
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if(userInput == -1)
break;
/* rest of loop body goes here */
}

I'm trying to identify the number of student entered in do-while , and display the number out-side the loop

I created the program that takes an input from the user,and display the number of student have been entered..
I use do-while loop because at the end of the program will ask the use "will you want to continue ?" if the user put y, it will loop again to get the input as well. I tried to make an array for it, but it didn't work well for displaying the number of student and the average grade as well...
#include<stdio.h>
int main ()
{
int student_id, test1,test2, final_mark;
float total_up;
char answer;
do {
printf("\nProgram to Calculate Student Grade\n");
printf("Insert the student ID: ");
scanf("%d",&student_id);
printf("\nInsert marks for Test 1 (total of 25 ): ");
scanf(" %d",&test1);
if (test1 >25)
{
printf("The marks is greater than 25.Please re-insert it again.");
printf("\nInsert marks for Test 1 (total of 25 ): ");
scanf(" %d",&test1);
}
printf("\nInsert marks for Test 2 (total of 25 ): ");
scanf(" %d",&test2);
if (test2 >25)
{
printf("The marks is greater than 25.Please re-insert it again.");
printf("\nInsert marks for Test 2 (total of 25 ): ");
scanf(" %d",&test2);
}
printf("\nInsert marks for Final Exam: (total of 50): ");
scanf(" %d",&final_mark);
if ( final_mark > 50 )
{
printf("\nThe Final Exam is greater than 50. Please re-insert it again.");
printf("\nInsert marks for Final Exam: (total of 50) ");
scanf("%d",&final_mark);
}
total_up = test1 + test2 + final_mark;
printf("Total Marks: %.2f",total_up);
if (total_up >=80)
{
printf("\nGrade is A\n");
}
else if (total_up >=60)
{
printf("\nGrade is B\n");
}
else if (total_up >=50)
{
printf("\nGrade is C\n");
}
else if (total_up >=40)
{
printf("\nGrade is D\n");
}
else if (total_up <40)
{
printf("\nGrade is F\n");
}
printf("Do you want to continue? ");
scanf(" %c",&answer);
}while (answer == 'y' || answer == 'Y');
printf("\nTotal number of students entered is %d ", student_id);
total_up = total_up / 2;
printf("\nTotal number of students entered is %.2f ",total_up);
return 0;
}
let say the input will be :
Program to Calculate Student Grade
Insert the student ID : 123
Insert marks for Test 1 ( total of 25 ): 15
Insert marks for Test 2 ( total of 25 ): 20
Insert marks for Final Exam ( total of 50 ): 42
Total Marks : 77.00
Grade is B
Do you want to continue ? y
Program to Calculate Student Grade
Insert the student ID : 456
Insert marks for Test 1 ( total of 25 ): 21
Insert marks for Test 2 ( total of 25 ): 23
Insert marks for Final Exam ( total of 50 ): 47
Total Marks : 91.00
Grade is A
Do you want to continue ? n
So, after the do-while terminates..
What I expect is
Total number of students entered is 2
Total number of students entered is 84.00
Average grade is A
I tried an array for student and the test, but it didn't work probably..
Any Idea about it?
For counting student and calculating subtotal, take two extra variables and initialize them to 0 outside the loop. Then, inside the loop, increment the student_count with each iteration of the loop and also add the total marks of current student with the variable of calculating subtotal. Finally, it is easy to calculate average. Just divide subtotal by the student count.
Also, for calculating grade, you can keep it inside another function, as you have to do it twice, once inside the loop and again outside the loop.
#include <stdio.h>
void showGrade(float marks)
{
if (marks >= 80) {
printf("Grade is A\n");
}
else if (marks >= 60) {
printf("Grade is B\n");
}
else if (marks >= 50) {
printf("Grade is C\n");
}
else if (marks >= 40) {
printf("Grade is D\n");
}
else if (marks < 40) {
printf("Grade is F\n");
}
}
int main()
{
int student_id, test1, test2, final_mark, student_count = 0;
float total_up, grand_total = 0, average;
char answer;
do {
student_count++;
printf("\nProgram to Calculate Student Grade\n");
printf("Insert the student ID: ");
scanf("%d", &student_id);
printf("\nInsert marks for Test 1 (total of 25 ): ");
scanf(" %d", &test1);
if (test1 > 25) {
printf("The marks is greater than 25. Please insert it again.");
printf("\nInsert marks for Test 1 (total of 25): ");
scanf(" %d", &test1);
}
printf("Insert marks for Test 2 (total of 25 ): ");
scanf(" %d",&test2);
if (test2 > 25) {
printf("The marks is greater than 25. Please insert it again.");
printf("\nInsert marks for Test 2 (total of 25): ");
scanf(" %d", &test2);
}
printf("Insert marks for Final Exam: (total of 50): ");
scanf(" %d", &final_mark);
if (final_mark > 50) {
printf("\nThe Final Exam is greater than 50. Please insert it again.");
printf("\nInsert marks for Final Exam: (total of 50): ");
scanf("%d", &final_mark);
}
total_up = test1 + test2 + final_mark;
grand_total += total_up;
printf("\nTotal Marks: %.2f\n", total_up);
showGrade(total_up);
printf("\nDo you want to continue? ");
scanf(" %c", &answer);
} while (answer == 'y' || answer == 'Y');
printf("\nTotal number of students entered is %d ", student_count);
average = grand_total / student_count;
printf("\nAverage total number of students entered is %.2f\n", average);
printf("\nAverage ");
showGrade(average);
return 0;
}
Initialize one variable to 0, for storing count of total number of student and increment it after accepting all data from user. At the end just print that variable as "Total number of students entered".`
int studentCount=0, studentTotal=0;
do {
// code to accept all data
studentTotal = studentTotal + total_up;
studentCount++;
}while(answer == 'y' || answer == 'Y');
printf("\n Total number of students entered is %d ", studentCount);
float studentAverage = studentTotal / studentCount;
if (studentAverage >=80)
{
printf("\n Average grade is A\n");
}
else if (studentAverage >=60)
{
printf("\n Average grade is B\n");
}
else if (studentAverage >=50)
{
printf("\n Average grade is C\n");
}
else if (studentAverage >=40)
{
printf("\n Average grade is D\n");
}
else if (studentAverage <40)
{
printf("\n Average grade is F\n");
}

C Program Limit the integer input range

I am a new C programming learner, I am trying to make a program which would calculate the GPA of a student on the basis of grade marks input and credits of a subject.
The problem I am having is I want to limit the number of subjects input from 2 to 6 only.
Another problem is I want to limit the user to input integer from 1 to 100 only, instead of any other keywords, special characters (EOF)
I have put the "###" in comment line where I require these modifications.
#include <stdio.h>
int main(void) {
// input user input -- hopefully a number
// temp used to collect garbage characters
// status did the user enter a number?
// counter for keeping track of loop repetition
// no no. of subjects to be entered by user.
// credits credits per subject
// grades grades acheived in each subject (1 to 100).
// grade_value for holding the value of each subject grade (for ex; 80 to hundred is 4.0)
// grade_points Grade points for each subject (credits * grade_value)
// sum sum of total grade points
int counter = 1, subjects, no, credits, grades, status, temp;
float grade_value, grade_point, sum;
printf("Enter number of subjects you took for current semester: ");
status = scanf("%d", & no);
// ### I want to limit this integer input to be >=2 && <=6.
while (status != 1) {
while ((temp = getchar()) != EOF && temp != '\n');
if ((temp < 2) && (temp > 6));
break;
printf("Invalid input... please enter the number of subject again: ");
status = scanf("%d", & no);
}
// ### I want to be this input to block other character inputs than integer from 1 to hundred.
while (counter <= no) {
printf("\nEnter Subject %d grades separated with credits \n", counter);
scanf("%d %d", & grades, & credits);
if ((grades > 0) && (grades <= 29)) {
grade_value = 0;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 30) && (grades <= 34)) {
grade_value = 0.67;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 35) && (grades <= 39)) {
grade_value = 1;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 40) && (grades <= 44)) {
grade_value = 1.33;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 45) && (grades <= 49)) {
grade_value = 1.67;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf(" \nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 50) && (grades <= 54)) {
grade_value = 2;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 55) && (grades <= 59)) {
grade_value = 2.33;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 60) && (grades <= 64)) {
grade_value = 2.67;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 65) && (grades <= 69)) {
grade_value = 3;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 70) && (grades <= 74)) {
grade_value = 3.33;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 75) && (grades <= 79)) {
grade_value = 3.67;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
} else if ((grades >= 80) && (grades <= 100)) {
grade_value = 4;
printf("Grade value for subject %d is: %.2f", counter, grade_value);
grade_point = credits * grade_value;
printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
sum = sum + grade_point;
++counter;
}
// To print a message if user doesnt enter an integer varying from 1 to 100.
else {
printf("\n Error Grade input, Please Key in Again. (1 to 100 only.)");
}
}
printf("\n");
printf("\n");
printf("\nThe GPA is: %.2f", sum);
if (sum <= 49) {
printf("\nYou can register for 2 subjects for next semester.");
} else if ((sum >= 50) && (sum >= 79)) {
printf("\nYou can register for 5 subjects for next semester.");
} else if ((sum >= 80) && (sum <= 100)) {
printf("\nYou can register for 6 subjects for next semester.");
}
printf("\n");
printf("\n");
printf("\n_______________________________________________________");
printf("\nEnd of program");
return 0;
}
A do-while loop is perfect for loops that need to be called at least once and will get rid of your duplicated code. Reading unstructured input, possibly from the keyboard, (one could call, ./a.out < text.txt,) is actually something that is tricky to get right.
Luckily, the C FAQ has lots of advice, eg, http://c-faq.com/stdio/scanfprobs.html. It's going to be very arduous without functions, though. From limited testing, I'm pretty sure that this is a solid way to read the first variable.
#include <stdio.h> /* fgets sscanf */
#include <stdlib.h> /* EXIT_ printf fprintf */
#include <string.h> /* strlen */
int main(void) {
int no;
/* Input number, no \in [2, 6], and make sure that the read cursor is on
the next line. */
do {
char buffer[80];
size_t len;
printf("Enter number of subjects you took for current semester, [2, 6]: ");
/* On the advice of http://c-faq.com/stdio/scanfprobs.html, this reads
into a buffer first. */
if(!fgets(buffer, sizeof buffer, stdin)) {
if(feof(stdin)) {
fprintf(stderr, "Premature EOF.\n");
} else {
/* On IEEE Std 1003.1-2001-conforming systems, this will print
a meaningful error. */
perror("stdin");
}
/* Can't really do anything interactive once stdin has a read
error. */
return EXIT_FAILURE;
}
/* This is always going to be true, but segfaults if not. Paranoid. */
if(!(len = strlen(buffer))) continue;
/* Normally fgets stores a '\n' at the end; check. */
if(buffer[len - 1] != '\n') {
/* Check if the length of the buffer is big enough to hold input. */
if(len >= sizeof buffer - 1) {
int c;
fprintf(stderr, "Line too long.\n");
/* Flush whole line. http://c-faq.com/stdio/stdinflush2.html */
while((c = getchar()) != '\n') {
if(c != EOF) continue;
if(feof(stdin)) fprintf(stderr, "Premature EOF.\n");
else perror("stdin");
return EXIT_FAILURE;
}
continue;
} else {
/* Non-POSIX lines, eg, file without '\n' terminating. */
fprintf(stderr, "Note: line without line break detected.\n");
}
}
/* Parse buffer for a number that's between [2, 6]. Ignore the rest. */
if(sscanf(buffer, "%d", &no) != 1 || no < 2 || no > 6) {
fprintf(stderr, "Invalid input.\n");
continue;
}
/* Now no \in [2, 6]. */
printf("no: %d\n", no);
break;
} while(1);
return EXIT_SUCCESS;
}
One may be able to get away with a subset of this if your teacher enters only well-formed numbers.
Your code has some semantic mistakes. You must never put a semicolon after a if statement. Also you can write a more legible code by spacing blocks of code. Even better, you could refactor some blocks and encapsulate it into functions. Aside of that, see this solutions:
For the first problem, it can be solved with few lines of code. It's a good practice that the user know the restrictions of inputs before enter his input:
/* ### I want to limit this integer input to be >=2 && <=6. */
#include <stdio.h>
int main()
{
int no;
do {
printf("Enter number of subjects you took for current semester (2~6): ");
scanf("%d", &no);
} while (no < 2 || no > 6);
return 0;
}
The other issue can be solved by using the Standard C Library. Just #include <string.h> and #include <ctype.h>
#include <stdio.h>
#include <string.h> /* strlen() */
#include <ctype.h> /* isdigit() */
int main()
{
int n, invalidInput, status;
char strInput[5];
int i; /* for loop */
do {
invalidInput = 0;
printf("Enter a **number** between 1 and 100: ");
fflush(stdin);
status = scanf("%4s", strInput); /* read at maximum 4 chars from stdin */
if (status > 3) {
continue; /* try again */
}
for (i = 0; i < strlen(strInput); ++i) { /* ensure that all characters are numbers */
if (!isdigit(strInput[i])) {
invalidInput = 1;
break;
}
}
if (!invalidInput) {
n = atoi(strInput); /* now your input is a integer */
if (n < 1 || n > 100) {
printf("Error: the input must be between 1 and 100.\n");
invalidInput = 1;
}
}
} while (invalidInput); /* repeat until all chars are digits and they are in the required interval */
return 0;
}

c programming language : the app wont stop after typing x

i made this program and its working just how i want but it should stop when i type x but it doesn't
can any one tell me why?
and if there is any shortcut or smaller way to type this code?
thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int meat[6];
int i;
int total =0;
int avg;
char what[20];
char end;
int days = 0;
char food[20];
char drink[20];
printf("what thing do u want to calculate the average of?(food/drink)\n");
scanf(" %s", &what);
if(strcmp(what, "food")==0)
{
printf("what sort of food did u ate ?\n");
scanf(" %s", food);
}
if(strcmp(what, "drink")==0)
{
printf("what sort of drink did u drank ?\n");
scanf(" %s", drink);
}
for(i=0; i<6; i++)
{
days++;
if(strcmp(what, "food")==0)
{
printf("how many %s did u ate in day %d\n", food, i+1);
}
else if(strcmp(what, "drink")==0)
{
printf("how many liters of %s did u drank in day %d\n", drink, i+1);
}
scanf(" %d", &meat[i]);
total += meat[i];
printf("if u want to continue type y\n");
printf("type x if u want to finish\n");
scanf(" %c", &end);
if((end = 'y')&&(i<5))
{
continue;
}
else if(end = 'x' && strcmp(what, "drink")==0)
{
avg = total / days;
printf("\nyour average amount of liters of %s you had %d\t the total is %d\n", drink, avg, total);
}
else if(end = 'x' && strcmp(what, "food")==0)
{
avg = total / days;
printf("\nyour average amount of %s you had %d\t the total is %d\n", food, avg, total);
}
break;
}
if(strcmp(what, food)==0)
{
printf("\nyour average amount of %s you had is %d\t the total is %d\n", food, avg, total);
}
else if(strcmp(what, drink)==0)
{
printf("\nyour average amount of liters of %s you had is %d\t the total is %d\n", drink, avg, total);
}
return 0;
}
else if(end = 'x' ...
should be:
else if(end == 'x' ...
You use == to test equality in if statements. You've got this in a couple places in your code, which is inadvertently performing an assignment, not what you want to achieve by comparing if user input is equal to a particular character.
Replace the = with == here:
else if(end = 'x' && strcmp(what, "drink")==0)
here:
else if(end = 'x' && strcmp(what, "food")==0)
and here:
if((end = 'y')&&(i<5))

C Reading list of numbers into multiple arrays

So I am trying to write a program that prompts the user to input how many data sets the user wishes to have, aka how many arrays there are going to be. It then prompts the user to input how many values will be in each data set and what the values are. Finally it gives the user a list of options to run on a desired data set.
When I run my code and select which data set I want to use, it seems to always come up with the last data set and doesn't seem to have all of the values in the set. I was just wondering if someone could let me know what I'm doing wrong or at the very least put me on the right track. I've gone through the code multiple times and can't figure it out.
#include <stdio.h>
int main()
{
unsigned short int num_sets, set_size, set_desired, command = 0;
printf("Enter the number of data sets you would like to store: ");
scanf(" %hu", &num_sets);
int i = 1, j, sets[1][num_sets], sum, a;
while(i <= num_sets)
{
j = 1;
printf("Enter the number of elements in data set %hu: ", i);
scanf(" %hu", &set_size);
printf("Enter the data for set %hu: ", i);
while(j < set_size)
{
scanf(" %d", &sets[i - 1][j - 1]);
j++;
}
i++;
}
printf("Which set would you like to use?: ");
scanf(" %hu", &set_desired);
while(set_desired > num_sets){
printf("There aren't that many data sets, try again: ");
scanf(" %hu", &set_desired);
}
printf("Set #%hu: %hu\n", num_sets, *sets[num_sets - 1]);
while(command != 7){
printf("Choose what you would like to do:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order.\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf(" %hu", &command);
if(command == 1){
printf("You picked 1!");
}
if(command == 2){
printf("You picked 2!");
}
if(command == 3){
/*printf("You picked 3!");
for(a = 0; a < set_size; a++){
sum = sum + *sets[a];
}
printf("%d\n", sum);*/
printf("You picked 3!");
}
if(command == 4){
printf("You picked 4!");
}
if(command == 5){
printf("You picked 5!");
}
if(command == 6){
printf("You picked 6!");
}
if(command == 7){
break;
}
}
}
If you are trying to store values in different sets than you need to maintain the number of items in each set separately as you don't know how many elements are there is each set.
The design should be such that:
Set 1 : Number of Elements : Actual values in the array.(Here I am storing the number of items in the set as part of the same array. It will be the first element in each set)
The memory allocation can be done dynamically as you are giving the option to the user to set the number of items per set.
#include <stdio.h>
#include<stdlib.h>
int main()
{
unsigned short int num_sets, set_size, set_desired, command = 0;
printf("Enter the number of data sets you would like to store: \n");
scanf(" %hu", &num_sets);
int *sets[num_sets];
int i = 0, k=0,j,sum, a;
while(i < num_sets)
{
j = 1;
printf("Enter the number of elements in data set %hu: \n", i+1);
scanf(" %hu", &set_size);
sets[i] = (int *) malloc((sizeof(int)*set_size));
*sets[i] = set_size;
printf("Enter the values for set %hu\n", i+1);
while(j <= set_size)
{
scanf(" %d", &sets[i][j]);
j++;
}
i++;
}
printf("Which set would you like to use?: \n");
scanf(" %hu", &set_desired);
while(set_desired > num_sets){
printf("There aren't that many data sets, try again: \n");
scanf(" %hu", &set_desired);
}
for(k=1;k<=(*sets[set_desired-1]);k++)
{
printf("Set #%hu: %hu \n", set_desired, *(sets[set_desired-1] + k));
}
while(command != 7){
printf("Choose what you would like to do:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order.\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf(" %hu", &command);
if(command == 1){
printf("You picked 1!");
}
if(command == 2){
printf("You picked 2!");
}
if(command == 3){
/*printf("You picked 3!");
* for(a = 0; a < set_size; a++){
* sum = sum + *sets[a];
* }
* printf("%d\n", sum);*/
printf("You picked 3!");
}
if(command == 4){
printf("You picked 4!");
}
if(command == 5){
printf("You picked 5!");
}
if(command == 6){
printf("You picked 6!");
}
if(command == 7){
break;
}
}
return 0;
}
You have undefined behaviour in your code. In this line:
int i = 1, j, sets[1][num_sets], sum, a;
you allocate enough space for one element in each of num_sets sets of data. This isn't really what you need. You probably want the num_sets as the first index, and you need a larger value for the other index.
You are likely to need to do dynamic memory allocation. Failing that, you'll need to set an upper bound (maybe 100) on the size of the arrays, and reject attempts to create bigger arrays. You'd then use:
enum { MAX_ARR_SIZE = 100 };
int sets[num_sets][MAX_ARR_SIZE];
for the variable. Your data entry loop already assumes this method of indexing. You probably need to keep a record of how many entries there are in each row somewhere, so as to avoid using uninitialized data.
int set_size[num_sets];

Resources