I wrote a code that count how many zeros, odds and evens are in the numbers provided by the user.
How do I need to change this code, so that in result i have :
Numbers from user without odds (for example if user writes 1234 i need that program will write 24)
Numbers from user without zeros. (for example if user writes 1005 i need that program will write 15)
Thank you.
int sk,a=0,b=0,c=0;
printf ("Write number: ");
scanf("%d", &sk);
while (sk!=0){
if (sk%10==0){
a++;
}
else if (sk%2==0){
b++;
}
else {
c++;
}
sk=sk/10;
}
printf(" Zeros %d \n Evens %d \n Odss %d ",a , b, c);
This may help :)
int sk,a=0,b=0,c=0;
int cnt_a=1,cnt_b=1,cnt_c=1;
printf ("Write number : ");
scanf("%d", &sk);
while (sk != 0){
if (sk%10 != 0){
a = a + (sk%10 * cnt_a);
cnt_a *= 10;
}
if (sk%2==0){
b = b + (sk%10 * cnt_b);
cnt_b *= 10;
}
else {
c = c + (sk%10 * cnt_c);
cnt_c *= 10;
}
sk = sk/10;
}
printf(" Without Zeros : %d \n Only Evens : %d \n Only Odds : %d ", a , b, c);
Change your 'printf' function, like above this, and you will receive your missing variables.
int sk,a=0,b=0,c=0;
printf ("Write number: ");
scanf("%d", &sk);
while (sk != 0) {
if (sk%10 == 0){
a++;
}
else if (sk%2 == 0){
b++;
}
else {
c++;
}
sk = sk/10;
}
printf(" Zeros %d \n Evens %d \n Odss %d \n Without Zeros: %d \n Without Odds: %d \n",a , b, c, b+c, a+b);
Related
I am making a program that counts how many passing grades there are based on the conditions. However, when I try calculating the percentage of passing scores, that is, if (passGrade >= 0) { printf("Percent of passing grades are %d! \n", (inputGrade/passGrade)*100); return 0; the program does not show the result, and instead shows up a zero, I did debug the program, and the passGrade, which is the number of total grades I entered in this line, shows up its value printf("You have entered %d passing grades! \n", passGrade); but when it comes to the next line, it just shows up a -1. I did look online for the problem, and nothing shows up.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int inputGrade, passGrade, percentGradePass;
inputGrade = 0;
passGrade = 0;
/* printf("Please type a grade (-1) to exit: ");
scanf("%i", &inputGrade);
printf("You typed: %i \n", inputGrade); */
while (inputGrade != -1)
{
printf("Please type a grade (-1) to exit: ");
scanf("%d", &inputGrade);
printf("You typed: %d \n", inputGrade);
if (inputGrade == -1)
{
inputGrade = -1;
}
else if (inputGrade >= 70 && inputGrade <= 100) {
passGrade = passGrade + 1;
}
else {
inputGrade = 0;
}
}
printf("You have entered %d passing grades! \n", passGrade);
if (passGrade >= 0) {
printf("Percent of passing grades are %d! \n", (inputGrade/passGrade)*100);
return 0;
}
}
Help would be much appreciated.
There are a number of issues with your code. Some issues are critical while others rather represents "strange/unnecessary" code.
Example with comments inline:
while (inputGrade != -1)
{
printf("Please type a grade (-1) to exit: ");
scanf("%d", &inputGrade); // ALWAYS, ALWAYS... check the return value of scanf
printf("You typed: %d \n", inputGrade);
if (inputGrade == -1)
{
inputGrade = -1; // Unnecessary! inputGrade is already -1 so no need to
// assign it again
}
else if (inputGrade >= 70 && inputGrade <= 100) {
passGrade = passGrade + 1;
}
else {
inputGrade = 0; // Unnecessary! inputGrade will get a new value from scanf
// in the next loop
}
}
So your loop could simply be:
while (inputGrade != -1)
{
printf("Please type a grade (-1) to exit: ");
if (scanf("%d", &inputGrade) != 1)
{
// Invalid input, terminate program
exit(1);
}
printf("You typed: %d \n", inputGrade);
if (inputGrade >= 70 && inputGrade <= 100)
{
passGrade = passGrade + 1;
}
}
Another potential issue is this:
(inputGrade/passGrade)*100
Since both variable have the type int the result of the division will be truncated to nearest integer, e.g. 6/10 will result in 0 instead of 0.6 and the whole expression will consequently become 0. To avoid that you can do the multiplication first (i.e. (100 *inputGrade)/passGrade) or use a floating point type instead of integer types.
That said, it seems that there is a basic misunderstanding in your algorithm. You say:
I try calculating the percentage of passing scores
To calculate the percentage you want
100 * NumberOfPassingGrades / TotalNumberOfGrades
but that is not what you are doing. Instead of using inputGrade in the calculation, you need to count the number of grades and use that in the calculation.
Something like:
int totalGrade = 0;
while (1)
{
printf("Please type a grade (-1) to exit: ");
if (scanf("%d", &inputGrade) != 1)
{
// Invalid input, terminate program
exit(1);
}
if (inputGrade != -1)
{
// Stop the loop
break;
}
printf("You typed: %d \n", inputGrade);
if (inputGrade >= 70 && inputGrade <= 100)
{
passGrade = passGrade + 1;
}
totalGrade = totalGrade + 1;
}
printf("You have entered %d passing grades! \n", passGrade);
printf("You have entered %d grades in total \n", totalGrade);
if (totalGrade > 0)
{
printf("Percent of passing grades are %d! \n", (100 * passGrade)/totalGrade);
}
what does 'the program does not show the result' means?
when your program reaches '(inputGrade/passGrade)*100)'
1/ you should check if 'passGrade' is 0 or not because if it is '0' there will be a run-time error.
2/ and also, since while loop is finished when 'inputGrade == -1', so you need to convert it to 'plus' before divide it
3/ lastly, since 'scanf("%d", &inputGrade);' means inputGrade = 'input' so, you dont need to write 'inputGrade = -1;' in your 'if' case
I just started programming a couple of days ago. I tried to program something that calculates my CGPA. I haven't completed it yet; for example, I have to improve the menu etc. It works properly for the 1st and 3rd choice. I will do something else for the second choice. The problem is, after calculation, it doesn't print the text "qwerty" on the bottom.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char h[2];
double numGrade;
double credit, percent, overallCredit, sumCredit;
double contribution=0, GPA=0, semGPA=0, CGPA=0;
int courseNum, i, semesters, k, menu;
printf("Input\n\"1\" for computing your CGPA\n\"2\" if you know each semester's GPA\n\"3\" if you know your CGPA\n");
scanf("%d", &menu);
if(menu == 1)
{
printf("Enter the number of semesters you have studied: ");
scanf("%d", &semesters);
for(k=1; k<=semesters; k++)
{
printf("Enter the number of courses you took in semester %d: ", k);
scanf("%d", &courseNum);
overallCredit = 0;
sumCredit = 0;
for(i=1; i<=courseNum; i++)
{
printf("Enter the credit of the course %d: ", i);
scanf("%lf", &credit);
overallCredit += credit;
printf("Enter your letter grade: ");
scanf("%s", h);
if(strcmp(h, "AA") == 0)
{
numGrade = 4.0;
}else if(strcmp(h, "BA") == 0)
{
numGrade = 3.5;
}else if(strcmp(h, "BB") == 0)
{
numGrade = 3.0;
}else if(strcmp(h, "CB") == 0)
{
numGrade = 2.5;
}else if(strcmp(h, "CC") == 0)
{
numGrade = 2.0;
}else if(strcmp(h, "DC") == 0)
{
numGrade = 1.5;
}else if(strcmp(h, "DD") == 0)
{
numGrade = 1.0;
}else if(strcmp(h, "FD") == 0)
{
numGrade = 0.5;
}else if(strcmp(h, "DD") == 0)
{
numGrade = 0.0;
}else
{
printf("Invalid Grade\n");
}
percent = numGrade/4.0;
contribution = percent*credit;
sumCredit += contribution;
}GPA = (sumCredit/overallCredit)*4.0;
printf("Your GPA for semester %d is: %f\n", k, GPA);
semGPA += GPA;
}CGPA = semGPA/semesters;
printf("CGPA is: %.2f", CGPA+0.005);
}else
{
printf("Enter your CGPA: ");
scanf("%lf", &CGPA);
printf("Your CGPA is: %.2f", CGPA+0.005);
}
printf("qwerty"); //This does not print.
return 0;
}
The problem here is that you're running into undefined behaviour! (This means anything can happen - code will work, sometimes, not work, sometimes, and maybe even wipe your hard disk, sometimes.)
This happens because you are trying to read too many characters into your h variable: you have declared it: char h[2], which can hold only one letter plus the terminating nul. But you try to read two letters into it. Declare it a bit longer: char h[3] and your code should work. But it's maybe better to be safer, and declare it longer, say char h[20];, in case the user types too much data in; alternatively, specify in the input format a maximum string length: scanf("%2s", h);, which will truncate (ignore) any letters after the second.
In your code, the scanf operation writes beyond the memory allocated to h and, thus, maybe changes other 'control' variables in the compiled code.
EDIT: PS, it may not actually be the scanf call that triggers the undefined behaviour! It could be the subsequent strcmp call - the h argument to this will not have a nul terminator and the function will then overflow the string buffer, looking for a zero.
When I'm trying to run without debugging the code everything runs smooth but as soon as I press Y so I can continue inputting numbers it terminates (gotta say I need help)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
The character read by getchar() is the pending newline that was typed after the number but was not consumed by scanf_s.
You should consume this pending newline before reading the next character for the continuation test, which can be done easily in scanf with a space before the %c conversion specification:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}
I need help regarding this... the problem in my c is when I execute this program and when I want to repeat the roll, the roll will not be displayed from 2nd time onwards... what do I do? I dont know what to do to fix this.. got stuck here
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, a, n, z;
char player[5][150], b, c;
float ave, total, f1, f2, f3;
total = 0;
ave = 0;
printf("\nPlease enter number of players : ");
scanf("%d", &a);
for (i = 0; i < a; i++)
{
printf("\nEnter player %d's name : ", i + 1);
scanf("%s", &player[i][150]);
}
printf("\nChoose the amount of dice used : ");
scanf(" %d", &n);
do
{
for (z = 1; z <= a; z++)
{
printf("\n\t%s\n ", player[z]);
if (n == 1)
{
do
{
f1 = 1.0 + 6.0 * ((float) rand() / RAND_MAX);
printf("\nRoll : %.0f\n", f1);
total = f1;
printf("Total : %.0f\n", total);
}while (f1 == 6);
}
else if (n == 2)
{
do
{
f1 = 1 + (rand() % 6);
f2 = 1 + (rand() % 6);
printf("\nRoll : %.0f,%.0f\n", f1, f2);
total = f1 + f2;
printf("Total : %.0f\n", total);
}while (f1 == f2);
}
else if (n == 3)
{
do
{
f1 = 1 + (rand() % 6);
f2 = 1 + (rand() % 6);
f3 = 1 + (rand() % 6);
printf("\nRoll : %.0f,%.0f,%.0f\n", f1, f2, f3);
total = f1 + f2 + f3;
printf("Total : %.0f\n", total);
}while (f1 == f2 && f2 == f3);
}
}
printf("\nRoll again ? (y/n) = ");
scanf("%s", &b);
}while (b == 'y');
printf("\n");
ave = total / n;
printf("Average : %.2f\n\n", ave);
return 0;
}
First thing is
scanf("%s", &b);
should be
scanf("%c", &b);
And you have to flush your stdin for your do while to work.
while ((c = getchar()) != '\n' && c != EOF);
The portable way to flush stdin
%s reads a C string, that is a null terminated char array. The shortest string containing 'y' is a 2 character array: "y" or { 'y', '\0'}.
So you should change char b; with char b[2];, and use it that way:
scanf("%1s", b);
}while (*b == 'y');
You current code writes (at least) a null after character b invoking undefined behaviour: anything can happen after that. But scanf("%1s", b); only reads first non blank character in b[0] and puts a null in b[1]: correct.
But IMHO, never mix input ignoring blank (space, tab, end of line) (%d%s%f...) with input explicitely processing them (%c, fgets), unless you are sure why you do it. So I will not advise you to use scanf("%c", b);
regarding this line:
scanf("%s", &b);
variable 'b' is a character, so it must be read as a character.
scanf(" %c", &b );
note: leading space in format string so leading white space will be skipped over
I need to write a simple program in C that makes simple calculations of: +,-,*,/
Now, I am using Visual Studio Express 2013, and here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf_s("%c", &o);
printf("Enter first operand\n");
scanf_s("%f", &a);
printf("Enter second operand\n");
scanf_s("%f", &b);
if (o == '+'){
sum = a + b;
printf("The result is", &sum);
}
if (o == '-'){
sum = a - b;
printf("The result is", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is", sum);
}
else printf("Error");
}
getchar();
}
My output: Enter operator
+
Enter first operand
3.5
Enter second operand
5.4
And after I type the second number- the program exits, and nothing!
There are no compilation errors, and I have no idea what to do. Can someone help, please?
You're not using printf correctly. This is what you're using.
printf("The result is", &sum);
You're not specifying the type of output in the format string, and you're passing the address of the variable you want to print, not the value.
You should use:
printf("The result is %lf\n", sum);
%lf is specifying that you want to print a double, \n adds a newline, and you pass the value of the variable sum, not it's address.
Also, you should change if (b == !0){ to if (b != 0){. If you leave what you put, it's the equivalent to if (b == 1){, which probably isn't what you want.
EDIT Here is the code, with my modifications, which gives correct results. I'll indicate which lines I changed
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
/* I had to use scanf, since I'm not using MS/Visual Studio, but GCC */
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a); /* changed %f to %lf */
printf("Enter second operand\n");
scanf("%lf", &b); /* changed %f to %lf */
/* I prefer to use if ... else if ..., this is personal preference */
if (o == '+'){
sum = a + b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '-'){
sum = a - b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '*'){
sum = a*b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '/'){
if (b != 0){
sum = a / b;
printf("The result is %lf\n", sum); /* Changed, see original post */
}
else printf("Error");
}
getchar();
return 0;
}
You are using %f format to read doubles. You should use %lf:
scanf_s("%lf", &a);
The print methods actually don't print the result (format is incomplete). And, instead of the value, you are passing variable's address. It should be:
printf("The result is %e", sum);
You should also change if (b == !0) to if (b != 0)
Now it's working fine I made some changes to it
the problem was with ur "scanf_s" and "%f" go throw with it
#include<stdio.h>
#include<stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%d", &a);
printf("Enter second operand\n");
scanf("%d", &b);
if (o == '+'){
sum = a + b;
printf(" The result is %d", sum);
}
if (o == '-'){
sum = a - b;
printf("The result is %d", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is %d", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is %d", sum);
}
else printf("Error");
}
getchar();
}