my function is not called after giving input to n - c

This might be a silly question, but I am unable to find the solution. Function mat is not being called after giving input to variable n.
#include <stdio.h>
#include <stdlib.h>
int mat(int n)
{
printf("hello");
int temp = n, count = 0;
while (temp != 0)
{
temp = n % 10;
switch (temp)
{
case 1:
count += 2;
break;
case 7:
count += 3;
break;
case 4:
count += 4;
break;
case 2:
case 3:
case 5:
count += 5;
break;
case 6:
case 0:
case 9:
count += 6;
break;
case 8:
count += 7;
break;
}
}
return count;
}
int main(void)
{
int t, n, h;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
h = mat(n);
printf("%d\n", h);
}
}
I think something is wrong with scanf but don't know what it is.
this program was to give the output for number of matches being used for particular number.

Forgive me. A common mistake of beginners is to "get into the weeds" without properly considering the nature of a problem. Lines and lines of code are written that fiddle with particular micro-aspects of the problem.
From the OP code, it appears you want to sum various amounts to a total based on the digits found in the user's number. Since 0-9 are "contiguous", a contiguous array of those values (with duplicates) can serve and reduce the amount of code that is copy/paste/adapted. You will spend many more hours READING code than writing code. Try to make the code as simple to understand (and reliable) as possible. Potential bugs will LEAP OFF THE SCREEN when you do this and your code will be appreciated by others.
#include <stdio.h>
#include <stdlib.h>
int mat( int n ) {
printf( "hello\n" );
// contiguous array of 10 values (some repeated)
int incr[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
int count = 0;
// sum from array values based on digits of value received
do {
count += incr[ n % 10 ];
} while( n /= 10 );
return count;
}
int main( void ) {
int t = 0; // ALWAYS initiaialise variables
scanf( "%d", &t );
while( t-- ) {
int n = 0; // declare variables close to use
scanf( "%d", &n );
// No need for 'h'. print returned value directly.
printf( "%d ==> %d\n", n, mat( n ) );
}
}

Related

Why this function gives me first sums correct and then prints bad sums

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;
} }

Strange behaviour in a Dice Throwing simulation program

I have written this piece of code which is supposed to simulate throwing dice many many times and counting that how many times each face is up. I have attached the output down there and as you can see it looks kind of strange. For example face 5 comes up exactly 10 times, faces 2, 3, 4 are about the same and face 6 comes zero in two rounds. The only face which acts about normal is 1.
Can anyone explain this to me? Is this normal? Am I doing something wrong or is it something related to my system?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
unsigned long int freq1, freq2, freq3, freq4, freq5, freq6;
unsigned long int L00p = 1;
unsigned short int DF;
while (L00p <= 6e7){
srand (time(NULL));
DF = 1 + (rand ()%6);
switch (DF)
{
case 1:
++freq1;
break;
case 2:
++freq2;
break;
case 3:
++freq3;
break;
case 4:
++freq4;
break;
case 5:
++freq5;
break;
case 6:
++freq6;
break;
default:
break;}
++L00p;
}
printf ("%s%25s\n", "Dice's Face", "Face Frequency");
printf ("1%25lu\n", freq1);
printf ("2%25lu\n", freq2);
printf ("3%25lu\n", freq3);
printf ("4%25lu\n", freq4);
printf ("5%25lu\n", freq5);
printf ("6%25lu\n", freq6);
return 0;
}
and here is the program's output after four times running it:
You don't initialize the frequency counters, so they'll likely contain garbage from the stack. (So yes, you were getting randomness, but not the randomness you want.)
You don't want to call srand() in the loop, but only once before it. Calling srand() with the same number (and time(NULL) will quite inevitably return the same second in a tight loop) will reset the rand() generator to return the same sequence of numbers, and since you only ever call rand() once before calling srand() again, you'll get a whole bunch of the same number.
The following version works fine, but you'd have a better time with an array.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
unsigned long int freq1 = 0, freq2 = 0, freq3 = 0, freq4 = 0, freq5 = 0,
freq6 = 0;
srand(time(NULL));
for (int loop = 0; loop < 1000; loop++) {
int DF = 1 + (rand() % 6);
switch (DF) {
case 1:
++freq1;
break;
case 2:
++freq2;
break;
case 3:
++freq3;
break;
case 4:
++freq4;
break;
case 5:
++freq5;
break;
case 6:
++freq6;
break;
default:
break;
}
}
printf("%s%25s\n", "Dice's Face", "Face Frequency");
printf("1%25lu\n", freq1);
printf("2%25lu\n", freq2);
printf("3%25lu\n", freq3);
printf("4%25lu\n", freq4);
printf("5%25lu\n", freq5);
printf("6%25lu\n", freq6);
return 0;
}
Example output:
Dice's Face Face Frequency
1 177
2 160
3 166
4 169
5 155
6 173
For reference, a version using an array of 6 ints:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
unsigned long int freqs[6] = {0};
srand(time(NULL));
for (int loop = 0; loop < 1000; loop++) {
freqs[rand() % 6] ++;
}
printf("%s%25s\n", "Dice's Face", "Face Frequency");
for(int face = 0; face < 6; face++) {
printf("%d%25lu\n", face + 1, freqs[face]);
}
return 0;
}
Here is an annotated adaptation of your code for educational purposes. You've learned about "loops", so here is an application for a do/while() loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Global variables are frowned upon because as the code grows more complex
// it is difficult or impossible to see where a value may be changed (inappropriately)
// For a tiny program like this that is unlikely to grow
// this proves the global variables are, by default, initialised to zero.
unsigned long int freq1, freq2, freq3, freq4, freq5, freq6;
int main() {
unsigned long int L00p = 0; // "local" var initialised. Good!
srand( time( NULL ) ); // called once at start of program.
do {
switch( ( rand() % 6 ) ) { // braces consistent with your main()
case 1: ++freq1; break; // get used to base-0 counting
case 2: ++freq2; break;
case 3: ++freq3; break;
case 4: ++freq4; break;
case 5: ++freq5; break;
case 0: ++freq6; break; // Ha-ha!! modulo!!!
default: printf( "A miracle has happened!!\n" );
break;
} // DO NOT hide that closing brace as you did. Prominent!
} while( ++L00p < 6e3 ); // increment counter after each loop done
// Swapped your output columns
// Using one format specifier for header and one for counts
// Notice how easy to modify only one instance?
char *tFmt = "%9s : %s Loops = %d\n";
char *oFmt = "%9lu : %d\n";
printf( tFmt, "Frequency", "Face", L00p );
// and... why not???
for( L00p = 0; L00p < 6; L00p++ ) {
int n; // not init'd because used immediately
switch( L00p ) {
case 1: n = freq1; break;
case 2: n = freq2; break;
case 3: n = freq3; break;
case 4: n = freq4; break;
case 5: n = freq5; break;
case 0: n = freq6; break;
}
printf( oFmt, n, L00p + 1 );
}
return 0;
}
Output
Frequency : Face Loops = 6000
958 : 1
1038 : 2
1018 : 3
1031 : 4
956 : 5
999 : 6
Again, for a simple, small piece of code like this, being able to see the entire switch block and compare values at a glance, concatenating statements can AID in writing bug-free code.

Why is this skipping numbers when I divide it?

Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BUFFER 512
void getCount(int *numCount, int *count);
int sumNumbers(int *numSum, int *sumNumOutput);
int main(void) {
printf("Enter a number greater than 0: ");
char string[BUFFER];
int numMain = 0;
int countMain = 0;
int sumNumMain = 0;
fgets(string, BUFFER, stdin); // gets user input and stores it in string
numMain = atoi(string); // converts the string to numerical and sets sum to the value. If there is a letter in the string, it will be zero.
int numCountMain = numMain;
int numSumNum = numMain;
getCount(&numCountMain, &countMain); // gets how many integers there are
sumNumbers(&numSumNum, &sumNumMain);
printf("Count: %d\n", countMain);
// printf("Sum: %d\n", sumNumMain);
return 0;
}
//shows how many integers were entered
void getCount(int *numCount, int *count){
while(*numCount > 0){
*numCount /= 10;
++*count;
}
return;
}
int sumNumbers(int *numSum, int *sumNumOutput){ // make it so that it isolates a number, then adds it to a universal sum variable
int increment = 1;
int count = 0;
while(*numSum > 0){ // gets the count of the number
while(*numSum > 0){
*numSum /= increment;
++count;
printf("numSum: %d\n",*numSum);
increment *= 10;
}
}
}
Let's say I put in 12345 as the number. It counts the number of digits in there just fine, but when it gets to isolating the individual digits using division, it skips over the third number. In the case of 12345, it would be:
12345
1234
12
0
I'm thinking this is a case of the increment running amok, but I can't find a fix for this. Also I know when I fix this, it will not solve the problem that I have to isolate the individual numbers. That's where the increment comes in and I know I have to use the modulus, but if someone can help me out with that after I take care of this, that would be great too.
Also, in case it isn't obvious, the code that has the problem I'm assuming is the bottom lines.
You are dividing by 1, 10, 100, 1000. So you are getting 12345, 1234, 12.
Try
while (*numSum > 0) {
++count;
printf("numSum: %d\n",*numSum);
*numSum /= 10;
}

Finding the largest even digit in a given integer

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.

I can't store integers inside an array

This is an activity given by my instructor.
Create a program that accepts numeric input from the user. If the user enters an even number, store it to an array for even numbers. If the user enters an odd number, store it to another array for odd numbers. Input terminates if the user entered 10 numbers already. Display the size of each array and their elements.
Example:
Input: 5, 6, 12, 10, 0, 3, 4, 100, -1, 7
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
and this is the code I've come up with.
#include <stdio.h>
int sort(int);
int main(){
int input, count;
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
sort(input);
}
printf("%d", input);
return 0;
}
int sort(int inp){
int odd[10];
int even[10];
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Please help me on how to store the numbers into two separate arrays. Any tips will be greatly appreciated.
Check the below code. It's self-explaining.
#include <stdio.h>
#include <stdlib.h>
#define NUM 10
int main()
{
int input, i;
int oddcounter = 0, evencounter =0;
int oddarr[NUM];
int evenarr[NUM];
printf("Enter 10 integers\n");
for (i = 0; i < NUM; i++)
{
if ( scanf("%d", &input) == 1 )
{
if ((input % 2) == 0)
{
evenarr[evencounter++] = input;
}
else
{
oddarr[oddcounter++] = input;
}
}
}
printf("Number of elem in oddarray : %d, evenarray : %d\n\n", oddcounter, evencounter);
printf("Odd elements are :");
for (i = 0; i < oddcounter ; i++) printf("%d\t", oddarr[i]);
printf("\n");
printf("Even elements are :");
for (i = 0; i < evencounter; i++) printf("%d\t", evenarr[i]);
printf("\n");
return 0;
}
In addition to Sourav's comment which indicates that you shouldn't have the int[] arrays be local to sort, this syntax isn't correct for assigning to arrays in C:
odd[]=inp;
On my compiler, it generates the following error:
24:9: error: expected expression
odd[]=inp;
To store to odd, you need to indicate the index at which you'd like to store, for example:
odd[1]=inp;
which also means you'll need to keep track the latest index you wrote to for each array!
You need to tell the compiler which index of the array you are storing your data to. In sort:
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Should look something like:
if(inp%2==0){
odd[endofoddindex]=inp;
}
else
even[endofevenindex]=inp;
return 0;
}
That said, you won't get much use out of the arrays being local variables, since they are deallocated on each call. Your best bet is to declare the arrays in main and pass them in.
Your even and odd arrays are both local. This means that they exist as long as the function exists. So you won't be retrieve the data you have stored(You also don't store it correctly).
So you need both the arrays in main and also two other variables for using as the index of both the array(i and j in the below program). The modified program is given below:
#include <stdio.h>
int sort(int);
int main(){
int input, count,i=0,j=0; //i and j to be used as array indices
int odd[10];
int even[10]; //arrays in main
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
if(sort(input)) //if odd number was found
odd[i++]=input;
else //even number found
even[j++]=input;
}
printf("%d", input);
//print even and odd arrays here
return 0;
}
int sort(int inp){
if(inp%2==0)
return 0; //if number is even,return 0
return 1; //else return 1
}
You need to either have your arrays as globals or pass them into your sort function. Where they are they currently they get recreated every time the sort function is called and are inaccessible to the rest of your program.
You will also need to keep track of the max number of ints in each array and the current number.
Your test in sort would be something like this:
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ currentEvenCount ] = inp;
currentEvenCount++
}
else
{
//TODO check that currentOddCount < maxOddCount
odd[ currentOddCount ] = inp;
currentOddCount++;
}
To declare your arrays as globals just move the declaration outside of any function above anywhere they are referenced
int even[10];
int odd[10];
int main() ...
To pass them as parameters to sort function you could declare sort like this:
sort( int inp, int even[], int maxEvenCount, int* currentEvenCount, int odd[]. int maxOddCount, int* currentOddCount)
{
...
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ *currentEvenCount ] = inp;
(*currentEvenCount)++
}
}
The * in front of currentEventCount is dereferencing the pointer and getting/setting the actual value pointed to.
You would then call sort like so:
int main()
{
int evenArray[10];
int oddArray[10];
int currentEvenCount = 0;
int currentOddCount = 0;
...
sort( input, evenArray, 10, &currentEvenCount, oddArray, 10, &currentOddCount);
}
There is no any sense to define the arrays as local variables of function sort because each time the function is called the arrays are created anew.
The program could look the following way
#include <stdio.h>
#define N 10
enum Type { Even, Odd };
enum Type sort( int x )
{
return x % 2 == 0 ? Even : Odd;
}
int main( void )
{
int odd[N];
int even[N];
int odd_count = 0;
int even_count = 0;
int i;
printf( "Enter %d numbers: ", N );
for( i = 0; i < N; i++ )
{
int num;
scanf( "%d", &num );
switch ( sort( num ) )
{
case Even:
even[even_count++] = num;
break;
case Odd:
odd[odd_count++] = num;
break;
}
}
printf( "Even numbers (%d):", even_count );
for ( i = 0; i < even_count; i++ ) printf( " %d", even[i] );
printf( "\n" );
printf( "Odd numbers (%d):", odd_count );
for ( i = 0; i < odd_count; i++ ) printf( " %d", odd[i] );
printf( "\n" );
return 0;
}
If to enter
5 6 12 10 0 3 4 100 -1 7
then the output will be
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
Simply copy, paste and investigate the program.:)
Hope this program will solve you issue. Here is the working code.
#include <stdio.h>
int sort(int[]);
int main(){
int input[10], count;
printf("Enter 10 digits: ");
for(count=0;count<10;count++){
scanf("%d", &input[count]);
}
sort(input);
return 0;
}
int sort(int inp[]){
int odd[10];
int even[10];
int oddCount=0, evenCount=0;
int i;
for(i=0; i<10;i++)
{
if(inp[i]%2==0){
even[evenCount]=inp[i];
evenCount++;
}
else
{
odd[oddCount]=inp[i];
oddCount++;
}
}
printf("ODD COUNT is %d \n", oddCount);
for(i=0; i<oddCount;i++)
{
printf("ODD VALUE %d \n", odd[i]);
}
printf("EVEN COUNT is %d \n", evenCount);
for(i=0; i<evenCount;i++)
{
printf("EVEN VALUE %d \n", even[i]);
}
return 0;
}
Your variable input is just an int, it's not an array. You need two arrays:
int even[10], odd[10];
Then you need to keep track of the number of numbers you've read so far, and for each number check which array to store it in.
I don't see a need to do sorting, so not sure why you have a function called sort().
It should just be something like:
int even[10], odd[10];
int oddindex = 0, evenindex = 0;
while(scanf(" %d", &x) == 1)
{
if(x % 2 == 0)
even[evenindex++] = x;
else
odd[oddindex++] = x;
if((evenindex + oddindex) >= 10)
break;
}
/* Loop here to print numbers. */
An answer suitable for an assignment question:
int main()
{
int i,c,o[10],e[10];int oc=0;int ec=0;int*pc;for(c=0;c<10;c++){scanf("%d",&i);pc=(i&1)?&o[oc++]:&e[ec++];*pc=i;}
// Now print out the values as requested in oc, o, ec and e.
}

Resources