C loop, beginner stuff - c

I have a task to make a program in which you have to input a given number on a given position in another given number. Example: input:12345, 2, 3 output 123245. I tried to make a loop but it is apparently an infinite loop. The code is here:
int c, x, p, broj, i = 0, brcifara = 0, k, broj2, k2, broj3, ind;
printf("Unesite redom x, p i c: ");
scanf("%d%d%d", &x, &p, &c);
broj2 = x;
while(broj2 >= 1)
{
broj2/= 10;
brcifara += 1;
}
while(i < brcifara)
{
k2 = pow(10, i + 1);
k = broj3%k2;
broj3 -= k*pow(10, i+ 1);
if(i<p)
{
broj += k*pow(10, i+1);
}
if(i=p)
{
broj += c*pow(10, p);
}
if(i>p)
{
broj += k*pow(10, i+2);
}
i = i + 1;
}
printf("Broj je sada %d", broj);
}
C represents the number for putting in, X is the number in which we are putting C, P represents the postion(starting from 0). Brcifara is the number of digits. The problem is only in the second loop.

Why not trying something like that :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define MAX_STR_SIZE (100U)
int main()
{
char x[MAX_STR_SIZE] = {'\0'};
unsigned int p;
char c;
int x_int;
printf("input x, p, c\n");
scanf("%s %d %c", x, &p, &c);
if(strlen(x) > p) // check string upper boundary
{
x[p] = c;
}
x_int = atoi(x);
printf("%d\n", x_int);
}
X is a string in which you replace your C character at the given P position.
Thus :
X is a string.
C a character.
P an index (unsigned char).
Then convert the X string to an integer using the atoi() function.

Related

C program which returns the sum of the digits of an integer

#include <stdio.h>
int main()
{
int sum=0, prod=1, a, b;
printf("Enter a number: \n");
scanf("%d",&a);
while (a!=0)
sum = sum + a%10;
a = a/10;
while (b!=0)
prod = prod + b%10;
b = b/10;
printf("Sum=%d\nProd=%d\n", sum, prod);
return 0;
}
This C program returns the sum and product of the digits of a given integer, but i want someone to break it down for me, and also when i ran it, it doesn't work, so can someone correct me, please.
% is the modulus operation, i.e. it gives you the reminder of the division by the divisor. In your case the operation % 10 effectively returns the last digit of the number. You sum this digit to the prod variable which represents the total sum of digits. Once you have summed the current digit you perform the next main operation / 10 which is integer divison and just removes the last digit of the number.
Your code is very badly indented and necessary block delimiters {} are missing. Also b is not initialized and you compute the sum, not the product of the digits.
Here is a corrected version:
#include <stdio.h>
int main() {
int n, sum, prod, a, b;
printf("Enter a number: \n");
if (scanf("%d", &n) != 1)
return 1;
a = n;
sum = 0;
while (a != 0) {
sum = sum + a % 10;
a = a / 10;
}
b = n;
prod = 1;
while (b != 0) {
prod = prod * (b % 10);
b = b / 10;
}
printf("Sum=%d\nProd=%d\n", sum, prod);
return 0;
}
As you're reading the number from the user, read a string.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[999];
while (fgets(buf, sizeof buf, stdin)) { // read a string rather than scanf an integer
buf[strcspn(buf, "\n")] = 0; // remove trailing newline
char *p = buf;
int invalidflag = (*p == 0);
unsigned sum = 0;
unsigned product = 1;
while (*p) {
if (isdigit((unsigned char)*p)) {
sum += *p - '0';
product *= *p - '0';
} else {
invalidflag = 1;
break;
}
p++;
}
if (invalidflag) {
printf("input = \"%s\" ==> INVALID INPUT\n", buf);
} else {
printf("input = \"%s\"; sum = %d; product = %d\n", buf, sum, product);
}
}
return 0;
}
See ideone.com/ZLkOfJ

Reversing a number with 0s in the last position in C

I've got this simple code for reversing integers. But I need to reverse numbers with leadings 0s now for another project. For example, this program is able to convert 32 to 23, but it converts 3200 to 23 as well. I need the 0s to stay in the leading place. However I've seen the binary operations on a bit level that can do this job, I'm looking for a way(if any) to do it without using bitwise operations and keeping it simple.
#include <stdio.h>
int main()
{
int a, mod = 0, reverse = 0;
printf("Enter a number:");
scanf_s("%d", &a);
while(a!=0)
{
mod=a%10;
reverse = reverse * 10 + mod;
a=a/10;
}
printf("%d", reverse);
return 0;
}
Record the scan offset with "%n" when reading the integer.
Use the text width of the number to control the reversal and printing.
int main() {
int a, mod = 0, reverse = 0;
printf("Enter a number:");
int n1, n2;
scanf(" %n%d%n", &n1, &a, &n2);
int width = n2 - n1;
while (width-- > 0) {
mod = a % 10;
reverse = reverse * 10 + mod;
a = a / 10;
}
printf("%0*d", n2-n1, reverse);
return 0;
}
Example
Enter a number:00123
32100
Enter a number:12300
00321
Other considerations not handled.
sign character '+' or '-'.
Input outside int range
Reversed number outside int range.
Non-numeric input.
I think you should approach this problem as if the input where a string.
#include <stdio.h>
#include <string.h>
#define MAX 15
void xor_swap(char *a, char *b) {
if(a != b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
}
int main(int argc, char **argv) {
char buffer[MAX];
size_t length;
printf("Enter a number: ");
fgets(buffer, MAX, stdin);
//fgets also includes the newline chracter so we get rid of that.
length = strlen(buffer);
buffer[length - 1] = '\0';
length--;
for(int i = 0; i < length / 2; i++) {
xor_swap(&buffer[i], &buffer[length - i - 1]);
}
printf("buffer: %s\n", buffer);
}
I would like to take slightly different approach.
I would request somebody to do the code indentation for me as I am using cell phone to answer.
# define SIZE 10
int main ()
{
int num= 3200;
// keep one array of characters to store the reversed digits.
char reversed_digit[SIZE];
int i= 0, temp;
if (num == 0)
reversed_digit[i] = (char) num;
else.
{
while (num > 0)
{
temp= num % 10;
num= num / 10 ;
reversed_digit[i++]= (char) temp;
}
reversed_digit[i]= '\0';
}
printf("The reversed digit is: %s ", reversed_digit);
return 0;
}

Switching the 2nd and 4th digit from right(rightmost) in a double

My question is pretty much the same as the question asked here: question
The difference is that I want to switch the 2nd and 4th digit from the right, instead of the left like in the other question. So rightmost number in my case is 1.
Example: 283926.67 becomes 282936.67.
How do I code this?
#include <stdio.h>
#include <stdlib.h>
int main() {
double number;
printf("Give a number: ");
scanf("%lf", &number);
//printf("%.4f", number);
char arr[sizeof(number)];
snprintf(arr, sizeof(number) + 1, "%f", number);
char ex = arr[1];
arr[1] = arr[3];
arr[3] = ex;
number = atof(arr);
printf("%.4f\n", number);
return 0;
}
You just have to do the exact same thing as in the link you've given:
int main() {
double A = 282936.67;
char str[50];
sprintf(str, "%f", A);
int dot = -1, i = 0;
//Finds the dot position
while (i != 50) {
if (str[i] == '.') {
dot = i;
break;
}
i++;
}
if (dot >= 4) {
char tmp = str[dot - 2];//Search from the dot position
str[dot - 2] = str[dot - 4];
str[dot - 4] = tmp;
}
//Convert your string to a float
A = atof(str);
printf("%.2f", A);
while (1);
return 0;
}

C program to find if a number is palindrome or not

I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...

Converting binary to number string to decimal number in C

I've written a program that asks the user to input a number using strings, the program then will convert that number to decimal, however Im having a problem with it, when I compile (using -lm) and run the a.out, I get a Segmentation fault (core dumped), not really sure where to look or how to fix it, also one more question what do i need so that it prints the result of the conversion (printf("something..")) ?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char string[100];
int s;
char a;
char j;
int sum;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
for(s = strlen-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,s);
}
}
}
return 0;
You probably meant to have strlen(string) - 1, not strlen - 1. My best guess is that your program is interpreting strlen as a function pointer, and it's pretty much a given that crazy things happen after that.
As it is, you might be interested in the strtol function, which appears to do exactly what you're looking for.
You use strlen as an integer. I think you mean strlen(string)
for(sum=0, j=0, s=strlen(string)-1; s >= 0; s--, ++j){
if(string[s] == '1'){
sum = sum + pow(2,j);
}
}
printf("%d\n",sum);
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
void reverse_string(char *string)
{
int string_length = strlen(string);
char temp;
int i;
for (i = 0; i < string_length/2; i++)
{
temp = string[i];
string[i] = string[string_length - (i + 1)];
string[string_length - (i + 1)] = temp;
}
}
int main()
{
char string[100];
int s;
char a;
char j;
int sum = 0;
int string_length = 0;
int number, original_number;
int remainder;
char binary_string[200];
int i = 0;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
a = toupper(a);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
string_length = strlen(string);
for(s = strlen(string)-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,string_length - (s + 1));
}
}
printf("%s in binary is %d\n",string,sum);
}
else if (a == 'D')
{
printf("enter positive decimal number to convert to binary: ");
scanf("%s",string);
number = atoi(string);
original_number = number;
if ( number < 0 )
{
printf("ERROR: only positive numbers please\n");
return 1;
}
do
{
remainder = number % 2;
if ( remainder == 0 )
binary_string[i] = '0';
else
binary_string[i] = '1';
number = number / 2;
i += 1;
}
while (number > 0);
binary_string[i] = '\0';
reverse_string(binary_string);
printf("decimal %d is %s in binary\n",original_number,binary_string);
}
return 0;
}
strlen isn't used properly. I think you want to do something like strlen(string)-1. BTW your logic wont work to convert the fractional part. Check this code:
#include <stdio.h>
#define MAX 1000
int main()
{
double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;
long dIntegral = 0,bIntegral=0,bFractional[MAX];
long intFactor=1,remainder,i=0,k=0,flag=0;
char fraBinary[MAX];
printf("Enter any fractional binary number: ");
scanf("%s",&fraBinary);
while(fraBinary[i]) //Separating the integral and fractional parts
{
if(fraBinary[i] == '.')
flag = 1; //If dot is found start taking the fractional part.
else if(flag==0)
bIntegral = bIntegral * 10 + (fraBinary[i] -48);
/* char - 48 to get the numerical value.*/
else
bFractional[k++] = fraBinary[i] -48;
i++;
}
while(bIntegral!=0){
remainder=bIntegral%10;
dIntegral= dIntegral+remainder*intFactor;
intFactor=intFactor*2;
bIntegral=bIntegral/10;
}
for(i=0;i<k;i++){
dFractional = dFractional + bFractional[i] * fraFactor;
fraFactor = fraFactor / 2;
}
fraDecimal = dIntegral + dFractional ;
printf("Equivalent decimal value: %Lf",fraDecimal);
return 0;
}
Source:
C Program to Convert Binary into Decimal Number

Resources