C coding interesting - c

#include <stdio.h>
int main (void) //starting entry of integer indicate not associated with any data types argument
{
int value1, value2, calculate = 0; //integer values
printf ("\nProgram should perform the following:");
printf("\n");
printf ("\nHave the user enter two different integer numbers to be divided by the program ");
{
printf ("\nIf the division of both numbers");
printf("\n");
printf ("\nresult with the remainder of zero,");
printf("\n");
printf ("\nby the second number.");
printf("\n");
printf ("Example: thirty-five divided by seven will have a remainder of zero");
printf ("\n");
}
printf ("Please enter the first integer number>>");
scanf ("%i", &value1);
printf ("Please enter the second integer>> ");
scanf ("%i", &value2);
if (value1 % value2 == 0 ) {
printf ("\n%i is evenly divisible by %i\n", value1, value2);
calculate = value1 / value2;
printf ("%i / %i = %i\n", value1, value2, calculate);
else
printf ("\n%i is not evenly divisible by %i\n", value1, value2);
return 0;
}
This code, that I have written is working correctly. But I can't seem to find which else or else if statement to use to make the code say Error: A zero is allowed in the program if the second number that the user enters is zero.

If you want to introduce such message for the user, you have to implement the condition to check for the numbers after the user has provided the input. which can be done like:
#include <stdio.h>
int main(void) //starting entry of integer indicate not associated with any data types argument
{
int value1, value2, calculate = 0; //integer values
printf("\nProgram should perform the following:");
printf("\n");
printf("\nHave the user enter two different integer numbers to be divided by the program ");
printf("\nIf the division of both numbers");
printf("\n");
printf("\nresult with the remainder of zero,");
printf("\n");
printf("\nby the second number.");
printf("\n");
printf("Example: thirty-five divided by seven will have a remainder of zero");
printf("\n");
printf("Please enter the first integer number>>");
scanf("%i", &value1);
printf("Please enter the second integer>> ");
scanf("%i", &value2);
if (value1 == 0 && value2 != 0)
{
printf("\nA zero is allowed in the program if the second number that the user enters is zero");
return 0;
}
else
{
if (value1 % value2 == 0)
{
printf("\n%i is evenly divisible by %i\n", value1, value2);
calculate = value1 / value2;
printf("%i / %i = %i\n", value1, value2, calculate);
}
else
{
printf("\n%i is not evenly divisible by %i\n", value1, value2);
}
}
return 0;
}

Don't use parentheses after printf, it changes nothing and use %d inside scanf and printf for integers. And close if parentheses before else.

Related

How can I take a variable multiple times and implement counters in while loop?

I want this program to determine if given integers are positive/negative & odd/even then increment the counters. But it doesn't work properly.
include <stdio.h>
int main() {
int evenCount=0, oddCount=0, posCount=0, negCount=0, zeroCount=0, m;
char x='x';
while(x!='y') {
printf("enter an integer\n");
scanf("%d", &m);
if((m>0)&&(m%2==0)){
posCount+=1;
evenCount+=1;
}
else if((m>0)&&(m%2!=0)){
posCount+=1;
oddCount+=1;
}
else if((m<0)&&(m%2==0)){
negCount+=1;
evenCount+=1;
}
else if((m<0)&&(m%2!=0)){
oddCount+=1;
negCount+=1;
}
else {
zeroCount+=1;
}
printf("if you want to end the loop write 'y'\n");
scanf("%c", &x);
}
printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);
return(0);
}
When I run it and give some numbers counts are at millions.
enter an integer
123
if you want to end the loop write 'y'
enter an integer
2
if you want to end the loop write 'y'
enter an integer
5
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564
The second example.
enter an integer
12
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564
I'm new to coding and this is my first post on this site also english is not my main language. I'm sorry if made any mistakes.
For starters you need to change this call
scanf("%c", &x);
to
scanf(" %c", &x);
Pay attention to the space before the conversion specifier.
And instead of trying to output addresses
printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);
you have to write
printf("odd %d \n", oddCount);
printf("even %d \n", evenCount);
printf("positive %d \n", posCount);
printf("negative %d \n", negCount);
And it is better to substitute the while loop
while(x!='y') {
//...
printf("if you want to end the loop write 'y'\n");
scanf("%c", &x);
}
for do-while loop
do {
//...
x = '\0';
printf("if you want to end the loop write 'y'\n");
scanf(" %c", &x);
} while ( x != 'y' && x != 'Y' );

C Wrong Answer when squaring

I'm learning C using C by Example. There is a question where we need to take an input integer and square it and print it to the screen. I'm having a strange error, when no matter what Int I enter it give me this output:
Please enter a number.
5
Number = 2686764 Square of Number = 2686760
Here is the program I wrote.
#include <stdio.h>
#include <conio.h> //for getch()
main(){
int number, square;
printf("Please enter a number. \n");
scanf("%d", &number);
square = number*number;
printf("\n Number = %d ", &number);
printf("\t Square of Number = %d", &square);
getch();
}
You are printing the memory address of the number and square variables, not their values.
Try this instead:
printf("\n Number = %d ", number);
printf("\t Square of Number = %d", square);
Your printf statements are incorrect. Do not use & in this case:
printf("\n Number = %d ", number);
printf("\t Square of Number = %d", square);
To add to the above answers ... look at this example:
int number = 5;
printf(" %d\n", number); // Prints value of 'number'.
printf(" %p\n", &number); // Prints address of 'number'.
printf(" %d\n", *(&number)); // Prints value at address of 'number' ...

How do I only accept numbers in C and block the user from entering letters and special characters?

I just need to figure out how to give an error is the user enters anything that is not number. I already set the values of the code that cannot be passed or be gone under.
I just need to only accept numbers: if a letter or any type of special character is entered I want the program to just cancel itself. How can I do this?
#include <stdio.h>
#include <math.h>
int main(void) {
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
scanf ("%f", &base);
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
scanf("%f", &height);
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}
You cannot block the user from entering whatever he or she wants, but you can use the return value of scanf to decide if a valid value has been entered, and prompt the user for a correct input:
float base;
do {
printf("Please enter the value of base of the triangle: \n");
} while (scanf ("%f", &base) != 1 || base < .5 || base > 100);
This loop will continue until all three conditions are met:
scanf has returned exactly one item,
The value provided by scanf is greater than or equal to 0.5, and
The value provided by scanf is less than or equal to 100
scanf returns the number of variables that have been matched and filled with values succesfully.
just do:
int result = scanf ("%f", &base);
if(result != 1)
{
...//handle error
}
I think that you could read the input character by character and then check if it's a number and if it isn't you show your error message.
#include <stdio.h>
#include <math.h>
int main(void)
{
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
char c='\n';
char success=0;
base=0;
char dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
base=base*10+(c-48);
else{
base+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
c='\n';
success=0;
height=0;
dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
height=height*10+(c-48);
else{
height+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))//check if is the first time the user insert a dot
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}

Cannot complete dividing calculation in case. Quotient is 0.0. is there a way I can change int to float?

// 2.cpp : Sample Program with a menu
//Write a program that will use a menu
#include "stdafx.h"
#include<stdio.h>
#define Pi 3.14159
int main(void)
{
int digit1;
int choice;
int a, b, c; //user input for choice 3 & 4
int a1, a2;// User input for Choice 1
int divi;
int divisor;
/*Menu*/
printf("***** MENU *****\n");
printf(" 1 - Greater Than, Less Than, Or Equal?\n");
printf("\t In this selection, you will enter two integers. \n");
printf("\t The program will return'Greater Than' if the first\n");
printf("\t integer entered is less than the second,'Less than'\n");
printf("\t if the first integer is greater than the second, or\n");
printf("\t'Equal' if the two integers entered are equal\n");
printf(" 2 - Evenly Divisible\n");
printf("\t In this slection, you will enter two integers. \n");
printf("\t The program will test if the the first integer\n");
printf("\t is evenly divisible by the second. The program\n");
printf("\t will then return its result and display\n");
printf("\t the quotient rounded to the nearest thousandth\n");
printf(" 3 - Calculations with 2 integers\n");
printf(" 4 - Calculations with 3 integers\n");
printf(" 5 - Calculations with circles\n");
printf(" 6 - Quit\n");
printf("Please enter your choice: ");
scanf("%i",&choice);
printf("\n\n");
switch(choice)
{
case 1: //Greater than, less than, or equal
printf("Please Enter two integers: \n");
scanf("%i %i", &a1, &a2);
if (a1<a2)
printf("Greater Than\n");
else if (a1>a2)
printf("Less Than\n");
else if (a1=a2)
printf("Equal\n");
break;
case 2: //Equally Divisible
I need help with this part of the code. Getting 0.000 for the quotient.Why? What about these cases is making it not receive the integers? I tried to localize the integers with the curly brackets. What am I doing wrong?
printf("Please Enter two integers: \n");
{
int divi;
int divisor;
scanf("%i %i", &divi, &divisor);
float modQuotient = divi%divisor;
if (modQuotient!=0)
{
printf("%i is not evenly divisible by %i\n", divi, divisor);
printf("The quotient is %.3f\n", divi/divisor);
}
else
{
printf("%i is evenly divisible by %i\n", divi, divisor);
printf("The quotient is %.3f\n", divi/divisor);
}
}
break;
/*case 3: /*Calculations with 2 integers*/
case 4: /*Calculations with 3 integers*/
printf(" You have selected to do some calculations with 2
integers\n");
printf("Please enter your 3 integers: ");
scanf("%i%i%i",&a, &b, &c);
printf("The average of %i, %i and %i is %g\n\n",a, b, c, (a+b+c)/3.0);
break;
case 5: /*Calculations with circles*/
float radius;
printf("Please enter the radius of a circle: ");
scanf ("%g", &radius);
printf("\nThe diameter of a circle with a radius of %g units is %.2f units\n\n",
radius, radius*2);
printf("The circumference is of the circle with a radius of %g
units is %.2f units\n\n", radius, Pi*radius*2);
printf("The area of a circle with a radius of %g units is %.2f
square units\n\n", radius, Pi*radius*radius);
break;
case 6: /*Quit*/
printf("Thank you. Good bye\n\n");
break;
default: /*Invalid Entry*/
printf("Invalid Entry...\n");
break;
}
printf("The program will now end. Have a great day!\n");
return 0;
}
The modulus of two ints is another int. Also, dividing by zero causes undefined behaviour. So you should write:
if ( divisor == 0 )
exit(EXIT_FAILURE); // or some other error handling
int modQuotient = divi % divisor;
and remember to use %i or %d if you are printf'ing modQuotient.
In the line:
printf("The quotient is %.3f\n", divi/divisor);
there is a problem. divi and divisor are both int, therefore the result of binary operation on them is also int. With printf it does not do any conversion of arguments to match the format specifier - you have to manually ensure the match yourself. So this code causes undefined behaviour by using %f to try and print an int.
If you want to do a floating point division then you must make at least one of the operands be a float, e.g. (and separating into two lines for clarity):
float quot = (float)divi / divisor;
printf("The quotient is %.3f\n", quot);
NB. You have a logic error in this code:
else if (a1=a2)
printf("Equal\n");
The = operator means assignment. This line changes a2 to be equal to a1. The operator to compare for equality is ==.
printf("The quotient is %.3f\n", divi/divisor);
In the above code you are telling the program the format the output as a float with precision out to three decimal places. So when the division occurs, if the answer were to be 0, it will instead output as 0.000.

Average of entered numbers in C - sum always 0

Here is a code which evaluates the average of 10 entered numbers. Problem is it doesn't seem to print the sum correctly (it's always equal to 0) after exiting the loop, everything else is working fine.
int count=0, n=10, c;
float sum=0, x;
do{
printf("x=");
scanf("%f", &x);
count++;
sum+=x;
}
while(count<n);
printf("Sum is %d", sum);
printf("\nCount is: %d", count);
printf("\nThe Average of the numbers is : %0.2f", sum/count);
getch();
}
Another question is how to exit the loop after a symbol is reached(i.e. without setting a limit to the number of integers to be entered).
Use the %f format specifier for floating point numbers.
printf("Sum is %f", sum);
To exit the loop on a symbol, you could check the return value from scanf. scanf returns the number of items read. If it returns 0 then the user didn't type a valid number.
while (1) {
printf("x=");
if (scanf("%f", &x) != 1) {
break;
}
...
}
break exits the current loop.
To answer your first question it should be printf("%f",sum) to print the correct sum. Since you are using float you have to use %f, if you use int it is %d. For your second question, you can do something like this (modify it accordingly):
int main(){
// Declare Variables
int count = 0; float sum = 0, currentNum = 0;
// Ask user for input
while(currentNum > -1)
{
printf("Enter integer to be averaged (enter -1 to get avg):");
scanf("%f",&currentNum);
if(currentNum == -1)
break;
// Check the entered number and computed sum
printf("You entered: %0.2f\n", currentNum);
sum += currentNum;
printf("Current sum: %0.2f\n", sum);
count++;
}
// Print Average
printf("Average is: %0.2f\n", sum/count);
return 0;
}
To answer your second question, you could do this:
scanf("%f", &x);
if (x==0) {
break;
}
This will break you out of the loop if you enter 0, then your loop can be infinite:
do {
} while(true)
For the second question, I think EOF may be the better solution:
while(scanf("%f", &x) != EOF)

Resources