Converting A1 to R1C1 format - c

As a follow up to my last question here.
I was trying out the reverse of the previous question. That is, converting an input of the form A1 to output of the form R1C1 (for more, look at my last question).
I'll explain my algorithm. Let us suppose we need to convert BC23 to R23C55. I extracted 'BC' and '23' from BC23 and stored them in seperate arrays. I made another array which stores values 1,2,3...so on for A,B,C respectively as and when they come in input. For example my array would contain 2 and 3 as first two elements respectively for B and C. Then I used some mathematics to convert it into a number, in this case 55 for BC.
Here is the complete code.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char str[5],col[5],row[5];
int i=0,j=0,k=0,lenOfstr,lenOfcol;
scanf("%s",str);
while(str[i]>='A'&&str[i]<='Z')
{
col[j]=str[i];
i++;
j++;
}
col[j]='\0';
lenOfstr=strlen(str);
lenOfcol=strlen(col);
int ascCol[lenOfcol];
for(i=lenOfcol;i<lenOfstr;i++)
{
row[k]=str[i];
k++;
}
row[k]='\0';
for(i=0;i<lenOfcol;i++)
{
ascCol[i]=col[i]-64;
}
int sum=0;
for(i=0;i<lenOfcol;i++)
{
sum=sum+(ascCol[i]*pow(26,lenOfcol-i-1));
}
printf("%d",sum);
return 0;
}
There is a slight bug in the last strip of code which I am not able to debug.
int sum=0;
for(i=0;i<lenOfcol;i++)
{
sum=sum+(ascCol[i]*pow(26,lenOfcol-i-1));
}
printf("%d",sum);
Input Z should give me output 26, and AA should give 27. But my code gives 26 on both. Thereafter output is always 1 less than what should be the correct output; BC gives 54 instead of 55.
Someone help me out.

Try changing the summation to this:
sum = sum * 26 + ascCol[i]
This avoids having to worry about unexpected floating point rounding behaviour and other issues caused by the fact that pow returns a floating point number.
Note you can simply your entire program to just this:
#include <stdio.h>
int main()
{
char str[5];
scanf("%s", str);
int i = 0;
int sum = 0;
while(str[i] >= 'A' && str[i] <= 'Z')
{
sum = sum * 26 + (str[i] - 'A');
i++;
}
printf("%d", sum);
return 0;
}

Related

converting array from binary to decimal

I'm converting a 4 bytes integer to binary, reversing the bits order, converting back to decimal and printing the integer. When I convert back to decimal somehow the number 49 get added to the correct number. Let my give you some examples:
decimal->binary -> reversed binary ->decimal(correct answer | my answer)
123->00000000000000000000000001111011->11011110000000000000000000000000->3724541952 | 3724542001
1->00000000000000000000000000000001->10000000000000000000000000000000->2147483648 | 2147483697
Everytime my answer - correct answer= 49 . Here is my code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
uint32_t f;
int a[32]={0};
int i;
int dec, j = 0;
printf("Enter a value :");
scanf ("%" SCNu32, &f);
for(i=0;f>0;i++)
{
a[i]=f%2;
f=f/2;
}
printf("\n Binary number(LSB) is=");
for(i=0;i<=31;i++)
printf("%d",a[i]);
printf("\n");
for(i=31;i>=0;i--)
{
dec = dec + (1u << i) * (a[j] - '0');
j++;
}
printf("The decimal representation:%u", dec);
return 0;
}
For converting back to decimal I used #Pras answer from here: Converting array of binary numbers to decimal
dec is not initialized.
- '0' is inappropriate because a[j] is a bit (0 or 1), not a character code ('0' or '1').
Either j is not needed (you can use 31-i) or it is not calculated correctly (should start at 31 and work down to 0 while i starts at 0 and works up to 31, or j can be calculated from i in each iteration).
With those errors corrected, the program produces the desired output. However, there are a number of other issues regarding the correct declaration of main and certain aspects of style, so here is a new version addressing some of them:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
// Declare main as "int main(void)" or "int main(int argc, char *argv[])".
int main(void)
{
uint32_t f;
int a[32] = { 0 };
/* Do not declare identifiers where you do not need them. This avoids
various errors that can occur where things are mistakenly used where
they were not intended.
i is used only in loops, so it is declared only inside those loops.
dec is only needed after some other work, so it is declared later.
j is not needed at all.
*/
printf("Enter a value:");
/* Do not put a space between a function and the parentheses for its
arguments.
*/
scanf("%" SCNu32, &f);
// Use more spaces; do not crowd symbols together.
for (int i=0; f>0; i++) // Or "for (int i = 0; i > 0; i++)".
/* Indent a loop body more than the code it is in; do not put { and }
further to the left and keep the loop body at the same indentation as
the code it is in.
*/
{
a[i] = f%2;
f = f/2;
}
printf("\nBinary number (LSB) is = ");
for (int i=0; i<=31; i++)
printf("%d", a[i]);
printf("\n");
/* Put blank lines in transitions between code that finishes one task,
like printing output, and code that starts another task, like
converting to binary.
*/
int dec = 0; // Declare dec here, just before it is needed.
for (int i=31; i>=0; i--)
{
/* Remove "- '0'" here. a[j] is a bit (0 or 1), not a character code
('0' or '1').
Do not use j. This loop has a counter, i. Using two counters for
different things may have confused you. While you want i to run
from 0 to 31, you want j to run from 31 to 0. You could use a
separate j for this, but it is easily replaced by 31-i.
*/
dec = dec + (1u << i) * a[31-i];
}
// Include spaces in output, like after the colon, to avoid crowding.
/* Print a "\n" at the end of each line of output. C is designed to use
"\n" to end lines, not to start them, because "\n" causes output to be
sent to interactive devices immediately instead of buffered.
*/
printf("The decimal representation: %u\n", dec);
return 0;
}

How to find if an int value contains a specific number?

Odd question, but I'm currently working on an assignment where I am asked to do the following:
Write a program that prompts the user for an integer between 1 and 1000, then prints from 1 to the entered number EXCEPT when the following conditions are met:
If the current number is a multiple of 3 OR contains a 3, print "Hello"
if the current number is a multiple of 7 OR contains a 7, print "Goodbye"
I understand how to determine if a number is a multiple of 3 or 7, but how would I determine if it contained a 3 or 7? I have all of my code written except for this part, and I am just a little lost and unsure what to do.
Thanks!
You should use mod % to find if somethings is dividable with 3 or 7.
To find the last digit of a number you should use mod 10 and then divide it by 10 to get the next digit.
The digits could also be obtained by using three nested loops from 0 to 10 with a break at final number or with a function like this:
#include <stdio.h>
int contains(unsigned long num,int x){
while(num){
if(num % 10 == x){
return 1;
}
num/=10;
}
return 0;
}
int main(){
printf("%d\n",contains(1237002,7));
printf("%d\n",contains(10000002,7));
printf("%d\n",contains(1234002,7));
printf("%d\n",contains(123002,7));
printf("%d\n",contains(7237002,7));
printf("%d\n",contains(1237007,7));
printf("%d\n",contains(7,7));
}
As #chux-ReinstateMonica suggested, you could print the integer to a buffer and then search for the '3' and '7' characters.
#include <string.h>
#include <stdbool.h>
bool contains_3_or_7(int num) {
char buffer[15];
sprintf(buffer,"%i",num);
return (strchr(buffer,'3') || strchr(buffer,'7'))
}
I think you must split the 2 parts:
First with your % comparaison which determine if it's a multiple like if (x % 7 == 0) (0 means x is a multiple of 7)
and for the seconde part convert your int into an str with itoa function or by coding your own like this:
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
then you can determine for each condition if they are true or false

C Programming: How to determine an exact match between 2 numbers

I am trying to find the exact match between two numbers and have my counter stop at the first instance when they are not a match. However the code I have written counts the entire string length of my numbers. Is there an alternative way to do this?
Since my counter is starting from the first decimal place and not 0. , it counts to 15 but should stop at 10.
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int main(){
char str[100];
char buf[100];
double l,m,a,b;
int c,d,t,u,r,q;
int count =0;
l=59874.141715197809000;
m=59874.141715197817000;
a= (l - (int)l);
b= (m -(int)m);
sprintf(str,"%.15f",a);
sprintf(buf,"%.15f",b);
c = strlen(str);
d = strlen(buf);
for(t=3;t<c;t++){
for(u=3;u<d;u++){
if(str[t]==buf[u]){
count++;
break;
}
}
}
printf("matching decimal places = %d \n",count);
return 0;
}
First, when comparing two strings, you only need to iterate to the length of the smallest string if the two strings differ in length.. That is, if you want to count the amount of sequential character matches in a string.
For example:
A = 0.99997552
B = 0.9999753
would need one for loop to compare.. You would only iterate up to the length of B to determine that 6 decimals match. Why? Because going any further is irrelevant since none of the extra digits would exist in B. Iterating past the end of an array is undefined behaviour anyway.
In your case both buffers are the same length so no worries there, but again, the shorter string won't have the extra digits found in the longer string.. Hence: Iterate up to the smallest length.
The solution can be done as follows:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main() {
//Create large enough buffer to hold 100 digits/characters..
char str[100] = {0};
char buf[100] = {0};
//Two doubles to be compared..
double l = 59874.141715197809000;
double m = 59874.141715197817000;
//Counter keeps track of matching digits..
int count = 0;
//Get rid of the base and keep only the decimals..
double a = (l - (int)l);
double b = (m - (int)m);
//Copy a maximum of 15 decimal places to `str` and `buf`
sprintf(str, "%.15f", a);
sprintf(buf,"%.15f", b);
//Get the length of both strings..
int c = strlen(str);
int d = strlen(buf);
//If C is smaller, iterate to length(c) else iterate to length(d).
for (int i = 2; i < (c < d ? c : d); ++i)
{
//If the two characters match, increment the count..
if (str[i] == buf[i])
{
++count;
}
}
//Print the amount of matching decimals..
printf("matching decimal places = %d \n", count);
return 0;
}
This may not be the answer, but do
if (number1 == number2)
{
// do something to stop it
}

Can't find the logical bug

I have solved this programming problem and when I submitted my code, the judge said it was wrong. I tried and I couldn't figure out the bug. Can someone give me a hint please?
Because stack overflow won't accept my question if I don't specify more details, I am copying the question here
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the
differences between successive elements take on all possible values 1 through n − 1. For
instance,
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively. The
definition implies that any sequence of a single integer is a jolly jumper. Write a program
to determine whether each of a number of sequences is a jolly jumper.
Input
Each line of input contains an integer n < 3, 000 followed by n integers representing the
sequence.
Output
For each line of input generate a line of output saying “Jolly” or “Not jolly”.
The code
#include <stdio.h>
#define SEQ_SIZE 3000
static char stack[SEQ_SIZE];
void initStack(int count)
{
for(int i=0;i<count; ++i)
stack[i]=0;
}
int absDiff(int a, int b)
{
return (a-b)>=0?((a-b)%SEQ_SIZE):(((a-b)*-1)%SEQ_SIZE);
}
int main()
{
int n,prev,curr;
/*FILE *sample=fopen("SampleInput","r");
if(!sample)
return 0;*/
while(scanf("%d",&n)!=EOF)
{
scanf("%d",&prev);
if(n<1)
break;
else if(n==1)
printf("Jolly\n");
else
{
int i;
for(i=1; i<n; ++i)
{
scanf("%d",&curr);
stack[absDiff(curr,prev)-1]=1;
prev=curr;
}
for(i=0; i<(n-1); ++i)
{
if(stack[i]==0)
break;
}
if(i<n-1)
printf("Not jolly\n");
else
printf("Jolly\n");
initStack(n);
}
}
}
I think your solution is fine except the line
return (a-b)>=0?((a-b)%SEQ_SIZE):(((a-b)*-1)%SEQ_SIZE);
No need to use % here. It should be
return (a-b)>=0?((a-b)): (a-b)*(-1));
To limit n below 3000 you can do as
if(n<1 || n >= 3000) // I merged it with n<1 condition
break;

Condition to check the value of variable in C

This is just for some extra credit, ive got a simple c program to calculate square roots, initially the program would just run away endlessly calculating them so i wanted a condition to check the value of the variable and if it is smaller or equal to i+(9^32) to loop round if not to print end.
Unfortunately i can't seem to get the if condition to work correctly
If any one has any suggestions would be great
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int m, i;
if ( argc > 1) {
m = atoi(argv[1]);
} else {
m = 1;
}
for( i = 1; i <= i+1; i++) {
double param, result;
param = i;
result = sqrt (param);
printf ("sqrt(%lf) = %lf\n", param, result );
sleep(0.5);
}
if( i <= (i + pow(9,32))
{ return (0); }
else { printf("end");
}
}
Add the condition in the test in your for loop:
for( i = 1; i < INT_MAX; i++) {
Note 1:
You should probably stop way earlier: few compilers have an int (or double) type that is big enough for 9^32. I've replaced it with the maximum int value.
Note 2:
The current condition i <= i+1 will cause the code to loop until i overflows. The overflow will result in undefined behaviour, although in most implementations i will wrap to a negative value causing the loop to terminate.
You need to read up on floating point precision. Hint: the numbers double implement are not like "real" real numbers, as used in math. There are limits, and 932 is a very large number, it's not certain that you can add it to another double and maintain precision.

Resources