I'm a student, and my task is "An integer X is given, find the maximum of the numbers included in its composition." For example X is 786534, so maximum number is "8". The task have to be done with function on c. I make some notes but it doesn't work correctly. There are two functions.
First function is for input number a check it for right size.
The second is for the calculating the max digit.
I have a problem with calling the function.
What is my mistake?
#include <conio.h>
#include <stdio.h>
#define MAX_N 999999999999
int inputNumber()
{
int number;
printf("Input number:\n");
scanf_s("%d", &number);
while (number = 0 && number > MAX_N)
{
// Number is not equal 0
printf("Repeat input:\n");
scanf_s("%d", &number);
}
return number;
}
int findMax(int number)
{
int max_number; //intermediate variable
int a = number;
max_number = a % 10;
a = a / 10;
while (a > 0)
{
if (a % 10 > max_number)
max_number = a % 10;
a = a / 10;
}
return max_number;
}
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
Okay, let's look at this:
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
inputNumber returns an int, but you don't store it somewhere. So this might work better for you:
int number = inputNumber();
findMax expects an argument, so this might work better:
int max_number = findMax(number);
That should get you further.
You need to save the return value of inputNumber() to a variable and pass that as the parameter to findMax(); variables such as "max_number" are limited by function scope.
I hope this helps!
Related
Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }
I am running this code, and the print commands are not actually resulting in any printing. Can anyone please advise? I do have a couple of comments at the end that will preface my two other functions, but for now, I am just interested in knowing why the prints aren't appearing even though my code doesn't show any errors.
Thanks!
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
return len;
printf("Length: %d", len);
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
return charsnum;
printf("First 2 digits: %ld", charsnum);
}
//Length & character count congruity
//Checksum
A function is terminated immediately after the return statement.
Your printing statement is after the return statement in those functions. That is why, they don't appear when you run the code.
So, put them before the return statement and you should be able to see them in the output. Moreover, for some clean output, do use \n inside those printf.
Then, inside your main function, look at these statements:
int length(long number);
int start_chars(long number);
Those are function declarations and not how functions are called in C. Store the return value in a variable. Since you just want to see those printf statements get executed, change that to:
length(number);
start_chars(number);
when you use return in your functions they will end immediately.
and so your printf line won't be executed.
printf should be before return.
Like the answers above, you made an error in your code where you are printing after the return statement.
Here is the correct code :
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
printf("Length: %d", len);
return len;
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
printf("First 2 digits: %ld", charsnum);
return charsnum;
}
//Length & character count congruity
//Checksum
I am taking an online C class, but the professor refuses to answer emails and I needed some help.
Anyways, our assignment was to write a program that takes an integer from the user and find the largest even digit and how many times the digit occurs in the given integer.
#include <stdio.h>
void extract(int);
void menu(void);
int main() {
menu();
}
void menu() {
int userOption;
int myValue;
int extractDigit;
do {
printf("\nMENU"
"\n1. Test the function"
"\n2. Quit");
scanf("%d", &userOption);
switch (userOption) {
case 1:
printf("Please enter an int: ");
scanf("%d", &myValue);
extractDigit = digitExtract(myValue);
break;
case 2:
printf("\nExiting . . . ");
break;
default:
printf("\nPlease enter a valid option!");
}
} while (userOption != 2);
}
void digitExtract(int userValue) {
int tempValue;
int x;
int myArr[10] = { 0 };
tempValue = (userValue < 0) ? -userValue : userValue;
do {
myArr[tempValue % 10]++;
tempValue /= 10;
} while (tempValue != 0);
printf("\nFor %d:\n", userValue);
for (x = 0; x < 10; x++) {
printf("\n%d occurence(s) of %d",myArr[x], x);
}
}
I have gotten the program to display both odd & even digit and it's occurrences.
The only part that I am stuck on is having the program to display ONLY the largest even digit and it's occurrence. Everything I've tried has either broken the program's logic or produces some weird output.
Any hints or ideas on how I should proceed?
Thanks ahead of time.
Run a loop from the largest even digit to smallest even digit.
for (x = 8; x >=0; x-=2)
{
if(myArr[x]>0) //if myArr[x]=0 then x does not exist
{
printf("%d occurs %d times",x,myArr[x]);
break; //we have found our maximum even digit. No need to proceed further
}
}
Note:To optimize you should count and store occurrences of only even digits.
Why do you even use the extra loop? To find the largest even digit in an integer and the number of its occurences, a modification to the first loop would suffice.
Consider the following (untested, but I hope you get the idea):
int tempValue;
int x;
int myArr[10] = { 0 };
int maxNum = 0;
tempValue = (userValue < 0) ? -userValue : userValue;
do {
int currNum = tempValue % 10;
myArr[currNum]++;
tempValue /= 10;
if (currNum % 2 == 0 && currNum > maxNum)
maxNum = currNum;
} while (tempValue != 0);
After this, maxNum should contain the largest even digit, and myArr[maxNum] should be the number of its occurences.
For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
maybe arrays are the solution. Any help would be appreciated. thank you!
You don't need array. Try something like this:
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.
If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.
Understanding this, we can then modify your code to take this into account:
int main() {
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0) {
if (n % 10 == 1)
count++;
n /= 10;
}
printf("Number of 1s in your number: %d", count);
return 0;
}
You may want to use convert your int to a string like this :
char str[100];
sprintf(str, "%d", n);
Then, you can just iterate on str in order to find the occurrences of your digit.
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}