Below is a simple program that the user enters the number of subjects taken --> the grade (A,B,C etc.) --> and the program calculates and prints the students transcript including all the cgpa.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[10];
char grade[10];
float out[10];
int num;
float cgpa=0.0;
for(int x=0;x<num;x++)
{
printf("\nEnter the number of subjects? \n ");
scanf("%d",&num);
printf("\nEnter Student Name: \n");
scanf("%s",&string[x]);
printf("\nEnter Student Grade: \n");
scanf("%s",&grade[x]);
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
else
printf("You've entered a wrong grade");
}
cgpa+=out;
cgpa=cgpa/num;
printf("%s\n", string);
printf("%s\n", grade);
printf("%f\n", cgpa);
getch();
}
My main problem is that I keep on getting the two following errors:
Cannot convert char to char*
illegal use of floating point
The errors I'm getting are on the following lines:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
The illegal use of floating point error is on this line:
cgpa+=out;
Please see solution. Your original solution had a lot of issues and is fundamentally flawed. The above commentary highlight most of the mistakes you've made, but the main flaw with your original solution was the lack of clear process structure.
Recommend drafting out your algorithm or process flow before you begin coding in future
1. Grab user input for student name and number of subjects
2. For every subject
a. Get user to input grade
b. Check grade is valid
c. Add to cumulative GPA value
Until num_subjects is met
3. Print out Student Name, Num Subjects and his GPA (cgpa/num_subjects)
See sample solution below, which adheres to the process I defined above.
I hope this assists you in your programming journey :)
#include <stdio.h>
// #include <conio.h> - Commented this out because this is MS Dos specific and makes solution non portable
#include <ctype.h>
int main(void)
{
int num_subjects;
char name[10];
char grade;
float cgpa=0.0;
int x;
// These do not need to be within your loop. Especially num_subjects
printf("\nEnter Student Name: \n");
scanf("%s", &name[0]);
printf("\nEnter the number of subjects? \n ");
scanf("%d", &num_subjects);
// I've replaced this with a while loop, because you need a continuous loop until a valid grade is required
while( x < num_subjects )
{
printf("\nEnter Student Grade: \n");
scanf("%c", &grade);
// Upper case the value, so there is no ambiguity in 'a' or 'A'
grade = toupper(grade);
printf("\nGrade Entered: %c\n", grade);
if (grade == 'A') {
cgpa+=4.0;
}
else if (grade == 'B') {
cgpa+=3.0;
}
else if (grade == 'C') {
cgpa+=2.0;
}
else if (grade == 'D') {
cgpa+=1.3;
}
else if (grade == 'F') {
cgpa+=0.1;
}
else {
printf("You've entered a wrong grade");
// Being lazy here. I'm decrementing the counter, because I am lazy.
// By right, the efficient thing to do is to increment the counter on a valid value
// But in the interest of writing less code, I've decided to decrement the value on an invalid value.
// And add more comments :P
x--;
}
// Increment x if a valid grade was entered.
x++;
}
// Final output line
printf("\nStudent: %s, Number Subjects: %d, GPA: %.2f", name, num_subjects, cgpa/num_subjects);
}
You can't add a whole array to a floating point number.
And grade [x] is a char while "A" is a char array.
Also you have to scanf your number before using it in your for loop.
Change this:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
For this:
if(grade[x]>='A' || grade[x]>='a')
out[x]=4.0;
Why?
reason 1: grade is an array of characters, not strings.
reason 2: == is a boolean operator (like the >= in your example). To set a variable value use just =
Study a little before coding. It is a very basic question.
Related
I am still new to C programming and need to figure out why when I enter the "c" choice the program isn't printing out the grades entered in the program. I am not seeing what I am missing, can someone let me know if they see what I am missing please?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Add all of the variables and the array for the grades I want to enter.
char choice;
int gradeScore = 0;//percentage
//int gradeArray[100];//percentArrray //Comment Out
int gCount = 0,i;//count
//Allocate dynamic memory point using gradeArray.
int *gradeArray = (int*)malloc(sizeof(int));
/*The for loop is set to enable the user to enter no more than 100 grades. This is because the gradeArray variable
limit is set to 100. This will then loop through until the user has entered up to 100 grades to ensure there
is no buffering issue.*/
for (gCount = 0; gCount < 100;)
{
/*This prompts the user for a choice that enables them to either enter another grade or exit the program and
print the grades. It also reads the choice entered by the user.*/
printf("******************Enter Choice Selection in Parenthesis******************");
printf("\n\n To add grades, enter choice (a)");
printf("\n When finished entering grades, enter choice (c) \n \nEnter Choice: ");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
/* Then I use an if with the condition set to a valid choice of 'a'. Then I prompt the user
to enter a grade, read it and move on to the next if statement.*/
if(choice == 'a')
{
printf("\nEnter grade: ");
scanf(" %d", &gradeScore);
/*If the grade entered does meet the if condition statement below it is added to the gCount
of grades entered. This will allow all of the grades entered to be printed with the exit condition.*/
if(gradeScore <= 100 && gradeScore >= 0)
{
gradeArray = realloc(gradeArray, sizeof(int) * gCount);
}
}
//The last if statement prints out each grade on a new line when the user choice is c.
if(choice == 'c')
{
break;
}
}
printf("Grades are:\n");
for(i = 0; i < gCount ; i++)
{
printf(" %d\%%\n", gradeArray[i]);
}
free(gradeArray);
return 0;
}
Thank you,
Annette
You are using wrong variable inside for loop according to your program. You are re-initialising gCount to 0 in for loop and not incrementing it. Later you are using same gCount to print grades. But since its value is 0 so no grades are printed.
Problem is that you never increased the value of a gCount variable, and for() loop is wrong too, I would recommend using while() here, also you never added gradeScore to gradeArray. You could write something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Add all of the variables and the array for the grades I want to enter.
char choice;
int gradeScore = 0;//percentage
//int gradeArray[100];//percentArrray //Comment Out
int gCount = 0,i;//count
//Allocate dynamic memory point using gradeArray.
int arr_size = 20;
int *gradeArray = malloc(sizeof(int)*arr_size);
/*The for loop is set to enable the user to enter no more than 100 grades. This is because the gradeArray variable
limit is set to 100. This will then loop through until the user has entered up to 100 grades to ensure there
is no buffering issue.*/
while(gCount < 100)
{
/*This prompts the user for a choice that enables them to either enter another grade or exit the program and
print the grades. It also reads the choice entered by the user.*/
printf("******************Enter Choice Selection in Parenthesis******************");
printf("\n\n To add grades, enter choice (a)");
printf("\n When finished entering grades, enter choice (c) \n \nEnter Choice: ");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
/* Then I use an if with the condition set to a valid choice of 'a'. Then I prompt the user
to enter a grade, read it and move on to the next if statement.*/
if(choice == 'a')
{
printf("\nEnter grade: ");
scanf(" %d", &gradeArray[gCount]);
/*If the grade entered does meet the if condition statement below it is added to the gCount
of grades entered. This will allow all of the grades entered to be printed with the exit condition.*/
if((gCount+1) == arr_size)
{
arr_size += 20;
gradeArray = realloc(gradeArray, sizeof(int) * arr_size);
}
gCount++;
}
//The last if statement prints out each grade on a new line when the user choice is c.
if(choice == 'c')
{
break;
}
}
printf("Grades are:\n");
for(i = 0; i < gCount ; i++)
{
printf(" %d\%%\n", gradeArray[i]);
}
free(gradeArray);
return 0;
}
Also, I want to point out that you shouldn't allocate array with just one element and constantly reallocate it. It is a bad practice, time-consuming, and can lead to some bigger problems later.
I recommend you to check this Do I cast the result of malloc? for malloc casting.
I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
Every time I run the program, the last "if" statement is not working, it means if I type "no", the loop won't break. Can someone please help me here?
#include <stdio.h>
int main() {
int age, i;
char ans;
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n continue?");
scanf(" %c", &ans);
if (ans == 'no') { // <-- here
break;
} else {
continue;
}
}
return 0;
}
use if (ans == 'n'). If you want to use the word "no", you have to change the type of variable ans to char array and use strcmp() method to compare strings.
In c programming single quotes (i.e. 'c') are used for characters and double quotes (i.e. "c") are used for strings. In double quotes last character is NULL.
Note: We cannot keep two characters in single quote like 'no'.
In your case first thing, declare ans as character array(i.e. string).
char ans[SIZE_AS_PER_REQUIREMENT];
To take input in this,
scanf("%s",ans);
For a better user experience before taking input give a proper message to user.
printf("\n Do you want to continue(yes/no)?");
Now to compare user's answer with program's condition, We have C-Language string library (i.e. string.h), include this before using any C-language inbuilt String function.
#include <string.h>
and use any of string function strcmp or stricmp as per requirement. Here I am going to use stricmp because it is possible that user may enter "no"/"No"/"NO". stricmp ignore the case.
stricmp(string1,string2)
It returns
Negative Number if string1 is less than string2
Zero if string1 equivalent to string2
Positive Number if string1 is greater than string2
So, for our case we check for Zero.
See the below program, I just added these in your code.
#include <stdio.h>
#include <string.h>
int main() {
int age, i;
char ans[5];//declare ans as character array
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n Do you want to continue(yes/no)?");
scanf("%s",ans);//take input as string in ans, its character array
if (stricmp(ans,"no") == 0) { // 0 means both are equal
break;
} else {
continue;
}
}
return 0;
}
You used %c which is for characters.
Instead, use %s.
The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}