Arbitrary specific integer c program - c

So, recently I've asked question about arbitrary specific integer calculator program. It scans two string and is supposed to calculate it's sum and difference, multiplication, division and modulus. So far I think I'm really close to finishing the sum difference and multiplication functions. Here is how my code look like for addition function:
void sum(char* a, char* b)
{
//initializing values
int len1,len2,i;
int carry=0;
char *r;
// counting the digits
len1=strlen(a);
len2=strlen(b);
// checking which array is longer
if (len1>=len2)
{
// if first array is longer we allocate enough memory for the result
r=(char*)malloc((len1+1)*sizeof(char));
// starting from the LSB
for (i=0; i<=len2; ++i)
{ // mod 10 to extract only the last digit of the sum
// that becomes our new digit
*(r+len1-i)=(*(a+len1-i) + *(b+len2-i) + carry)%10;
carry=(*(a+len1-i)+*(b+len2-i))/10;
}
// copying the rest of the digits
for (i=len2+1; i<=len1; ++i)
*(r+len1-i)=*(a+len1-i);
}
//case when the other number has more digits
else
{
r=(char*)malloc((len2+1)*sizeof(char));
for (i=0; i<=len1; ++i)
{
*(r+len2-i)=(*(a+len1-i)+*(b+len2-i)+carry)%10;
carry=(*(a+len1-i)+*(b+len2-i))/10;
}
for (i=len1+1; i<=len2; ++i)
*(r+len2-i)=*(b+len2-i);
}
// printing the result
printf("The result is: \n %s \n", r);
}
The problem is when I try to call for the function in main the end result just gives errors, even though there are not any errors while compiling the code. It might be a problem in main so here is how my main looks like.
int main()
{
FILE *fp;
char *fi=NULL, *se=NULL;
char o;
int i=0;
fp= fopen("/CalculatorHistory.txt", "r+");
opening();
fi=(char*)malloc(60*sizeof(char));
se=(char*)malloc(60*sizeof(char));
while(i<2)
{
first();
scanf("%s", fi);
// I am not sure when im saving pointer arrays, if it works like this
// or i should save it in a for loop
fprintf(fp, fi);
oper();
scanf(" %c", &o);
fprintf(fp, o);
second();
scanf("%s", se);
fprintf(fp, se);
switch (o)
{
case '+':
sum(fi, se);
case '-':
sub(fi, se);
case '*':
mul(fi, se);
case '/':
div(fi, se);
case '%':
mod(fi, se);
}
}
return 0;
}
I hope that somebody can help me. I'm pretty lost and still really new to c programming.

Related

Exiting a loop when a non-double input is typed

Basically the title, I am in a beginners C++ class and am trying to do an assignment but have been having trouble learning without the hands on teaching due to covid. I am trying to sum and average numbers using a while loop, but have it stop when a character or string is entered instead of a double. I think all of my code except the conditionals work, any help would be greatly appreciated.
#include <stdio.h>
int main(int argc, const char* argv[])
{
double userNum, numSum, numAvg;
int i; //iterations for calculating average
userNum = 0.0;
numSum = 0.0;
numAvg = 0.0;
i = 0;
while (1)
{
if (1) {
printf("Enter a score (or stop to quit):\n");
scanf("%lf", &userNum);
}
else // I thought this would break the loop if any nun double value was entered but I was wrong?
{
break;
}
numSum = numSum + userNum;
i++;
}
if (i == 0) // if no ittereations done, gives no sum message
{
printf("No sum and average calculated!");
}
else
{
// otherwise calculates and prints sum and avg
}
{
numAvg = numSum / i;
printf("The sum is: %0.2lf, average is: %0.2lf", numSum, numAvg);
}
return 0;
}
if(1) is redundant and by adding it, you are never going to reach else.
It is equivalent to if (1 != 0) which is always true.
You can achieve what you are asking by checking the return value of scanf(). You can modify your code like so:
while (1)
{
printf("Enter a score (or stop to quit):\n");
if (scanf("%lf", &userNum) != 1) // should return 1 if 1 double is read
{
break;
}
numSum = numSum + userNum;
i++;
}
For large inputs, I would suggests that you switch to fgets() and later parse the string with sscanf(). scanf() doesn't provide any protection from arithmetic overflow, which is undefined behavior.

How do I get the proper output for the color bands of a 3 band resistor?

I am taking a programming class as an elective. Our current lab is to create a program that accepts a number from the user that represents a resistor band. The max would be two digits followed by 9 zeros; 11 total digits. After accepting the number I have a few functions that find the first two digits, then the modulus for the second band and divide by 10 for the first. My issue lies in using a logarithm 10 function and even trying a loop with a counter to find the number of zeros. I have gotten it to be able to count 8 zeros, but once the ninth gets added it messes everything up including the first number. In my code I have some instruction or information and some functions stagnant as I hid them to try different options. I currently have just been trying to be able to enter 99000000000 and get "White" in return for all three numbers. Any ideas where I am going wrong?
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
long int inputValue();
void outputColor(int);
int bandCalc(long int);
int loop(long int);
int divideResistor(int);
// function prototypes // '''
int main()
{
int resistor, x, y, z, a, b, c, f;
resistor = inputValue();
//printf("\n\tThe resistor value is %d", resistor);//
c = resistor;
b = divideResistor(resistor);
f = loop(b);
//printf("\t\nThe number is %d", b);//
if (f <= 10)
{
f = log10(c) - 1;
}
else
{
f = log10(c) - 2;
}
//Here we are finding out how many zeros there are in the number//
printf("\n\tThe character x equals %d", x);
y = bandCalc(b); //Here we are getting the first two digits of the resistor value//
printf("\n\tThe character y equals %d", y);
z = fmod(y, 10); //Here we are finding the second digit of the resistor//
printf("\n\tThe character z equals %d", z);
a = (y / 10); //Here we are finding the first digit of the resistor//
printf("\n\tThe character a equals %d", a);
x = bandCalc(resistor);
printf("\n\tThe returned number is %d", x);
printf("\n\n\tThe color of the resistor bands are: \n\n");
printf("\n\t");
outputColor(a);
printf("\t ");
outputColor(z);
printf("\t ");
outputColor(f);
system("pause>nul");
return 0;
}
int divideResistor(int s)
{
s = s / 10;
return (s);
}
int loop(long int j)
{
int k;
k = 0;
if (j >= 100)
}
}
j /= 10;
k++;
for (j > 100; j /= 10; k++)
k <= 9;
printf("%d ", k);
return (k);
}
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band);
return (band);
}
int bandCalc(long int z)
{
long n = z;
long n1 = n, n2 = n;
while (n)
{
n2 = n1;
n1 = n;
n /= 10;
}
return (n2);
}
void outputColor(int i)
{
switch (i)
{
case 0:
printf(" Black");
break;
case 1:
printf(" Brown");
break;
case 2:
printf(" Red");
break;
case 3:
printf(" Orange");
break;
case 4:
printf(" Yellow");
break;
case 5:
printf(" Green");
break;
case 6:
printf(" Blue");
break;
case 7:
printf(" Violet");
break;
case 8:
printf(" Grey");
break;
case 9:
printf(" White");
break;
//return (band);//
}
}
Take a look at your inputValue function:
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band); // format-specifier for a "long int" is "%ld"
return (band);
}
You are using a long to store the input, but you are telling scanf that band is only an int, so it will only be able to store values as high as INT_MAX (2147483647 for 32-bit two's complement ints). Assuming long is a 64-bit type on your system, it will be able to handle much larger values (9223372036854775807).
Try fixing your scanf call there to use the %ld format-specifier: scanf("%ld", &band);
Similarly, look at the type of resistor which takes the return of inputValue. It is of type int, so it won't be able to handle values that are outside of that INT_MAX range. That should also be type long. You'll also need to modify the input of functions such as divideResistor to take a long.
Beyond the issues of not using large enough integer types, you are also using floating-point operations on integer-type data. which can create rounding errors. log10, for example, is meant to handle double types. fmod is also intended for double types (the % operator is used do perform 'modulo' operations on integer types)
There may be further errors beyond these. If you find yourself having more trouble, please give this link a look-over and see if it helps you to help yourself, or at least help you construct a Minimal Complete Verifiable Example of specific issues rather than a scavenger hunt to find all the errors in your full program.

Array gets ints from assignments of other variables in main. How is it possible?

I'm getting crazy with C. I'm writing code for my battleship DOS app. I'm using a int matrix (10x10) to build the field, but a weird thing happens. When I assign a value to an other variable, some points in the field change their value.
I don't know how it's possible.
I use to fill the matrix with '1' (int value), so I print a char to simulate a "sea point" on the battleship field. Here's the problem: some unwanted ints appear on the field.
I removed all the functions from the game, leaving only "printfield". It still happens. Please help!
(i'm italian, i tried to translate the variables names to make things easier. i'm sorry if i did some english errors. I also added a lot of printfield functions to see how the field changes during the app execution)
Here the code: (note: changing, for example, the "pos_x" assignment, the unwanted values change)
#include <stdio.h>
int printfield(int camp[][9]);
int fill(int campo[][9]);
int main()
{
int continua;
int field1a[9][9];
fill(field1a);
printfield(field1a);
continua=0; //what do this assignment do?????
while(continua==0)
{
printfield(field1a);
system("pause");
int pos_x=7; //what do this assignment do?????
printfield(field1a);
int pos_y=3; //what do this assignment do?????
printfield(field1a);
system("pause");
}
printfield(field1a);
system("pause");
system("cls");
printfield(field1a);
system("pause");
}
int printfield(int camp[][9])
{
printf("\n\n\n");
printf(" ");
int word;
for(word=97;word<=106;word++)
{
printf("%c ", (char)word);
}
int q, r;
for(q=0;q<=9;q++)
{
for(r=0;r<=9;r++)
{
if(r==0)
{
printf("\n");
if(q!=9) //to print '10' (the row number) correctly spaced -see the different number of spaces I put into the next printf
{
printf("%d ", q+1); //printf with 2 space for numbers 1-9
}
else
{
printf("%d ", q+1); //printf with 1 space for number 10
}
}
switch(camp[r][q])
{
case 1:
printf("~ ");
break;
case 2:
printf("0 ");
break;
case 3:
printf("S ");
break;
case 4:
printf("- ");
break;
case 5:
printf("X ");
break;
case 6:
printf("S ");
break;
case 7:
printf("- ");
break;
case 8:
printf("X ");
break;
default:
printf("E ");
break;
}
}
}
}
int fill(int campo[][9])
{
int f, h;
for(h=0;h<=9;h++)
{
for(f=0;f<=9;f++)
{
campo[f][h]=1;
}
}
}
You are trying to assign in a matrix[9][9] a number in a position [10].Remember a int [10] represents an array who starts at 0 until 9.
So, an array [9] starts at 0 to 8.
So you should or correct the matrix to be an matrix[10][10] or correct the for statement like that:
`for(q=0;q<9;q++)` (LESS **not** LESS EQUAL)
I hope I've helped you. I am not a native and my english is not good also.

How would I create a formula only using declared int's in C?

I'm not sure if I worded my question properly, but here is what I'm basically looking for. I'm currently working on an assignment for school practicing using functions in my code. I'm having trouble reusing a certain function by altering the operation in the function.
int ArithmeticOptionGame(int Operation)
{
int MaxNumber, AmtOfProblems, i, Answer = 0, Choice;
printf("What is the maximum number you would like?\n");
scanf("%d", &MaxNumber);
printf("How many problems would you like?\n");
scanf("%d", &AmtOfProblems);
int start = time(0);
for(i = 0; i < AmtOfProblems; i++)
{
int j = (rand() % MaxNumber) + 1;
int k = (rand() % MaxNumber) + 1;
printf("What is %d %d %d:\n", j, Operation, k);
/* What goes here for the answer formula */
scanf("%d", &Choice);
if(Choice == Answer)
{
printf("Correct! Great Job!\n");
}
else
{
printf("Sorry, that's incorrect. The answer is %d\n", Answer);
TotalScore -= 5;
}
}
int end = time(0);
TimeSpent = end - start;
TimeConvertedToScorePoints();
TotalScore /= AmtOfProblems;
return;
}
Depending on what I need for my operation whether it's +, -, /, *, etc. how would I code it under the printf line. I've already tried:
Answer = j Operation k;
Which I know is wrong, but figured I'd try. Again, not sure if this is even possible or would I need to just create a separate function for each operation?
Given that this is an assignment for an introductory class, I think that using an explicit switch statement would be the preferred way.
double
compute(const double lhs, const double rhs, const char op)
{
switch (op)
{
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
case '*':
return lhs * rhs;
case '/':
return lhs / rhs;
default:
fprintf(stderr, "error: unknown operation: %c\n", op);
abort();
}
}
I have intentionally altered the setting a little so you'll have to transfer the concept back to your exercise.

What's wrong with my implementation of POJ 1007?

Hi I'm new to competitive programming and this is my first problem. (Here's the link this problem - : POJ 1007 -- DNA Sorting). The problem is basically simple string manipulation and here's the solution that I've come up with.
// POJ id=1007 - DNA
#include<stdio.h>
int a[50][100];
void insert(char temp[], int i)
{
int j=0;
while(temp[j]!='\0')
{
switch(temp[j])
{
case 'A':
a[i][j]=0;
break;
case 'C':
a[i][j]=1;
break;
case 'G':
a[i][j]=2;
break;
case 'T':
a[i][j]=3;
break;
}
j++;
}
}
int main()
{
int i,j,unso[100],k,m,n,large,largeindex=0;
scanf("%d%d", &n, &m); // n -length 50max|| m - number of strings 100max
char temp[50];
char dna[50][100];
for(i=0;i<m;i++)
{
gets(dna[i]);
gets(temp);
insert(temp,i);
} // Inserted the string as an equivalent integer array
// HERE: Calculate measure of ``unsortedness'' for ith string and put it in unso[i] for all 0<=i<n
for(j=0;j<n;j++)
for(i=0;i<m;i++)
for(k=i+1;k<m-1;k++)
if(a[j][i]<a[j][k])
unso[j]++;
// HERE: Find the largest element in anso, note the corresponding 'i', print dna[i][100];
i=0;
do{
large=unso[0];
for(j=1;j<m;j++)
{
if(unso[j]>large){
large=unso[j];
largeindex=j;}
}
printf ("%s" , dna[j]);
unso[j]=0;
largeindex=0;
i++;
}while(i<m);
return 0;
}
Please help to find what's wrong with my implementation.

Resources