I have to add two digit strings, meaning 1234 12+34 (at least that's what i gather). I wrote a program that does this expect for one exception, that is when the last number doesn't have a pair it wont add properly.
Here is the code i have:
void main()
{
char string[1000];
int count,sum=0,x,y;
printf("Enter the string containing both digits and alphabet\n");
scanf("%s",string);
for(count=0;count < string[count]; count++)
{
x=(string[count] - '0') * 10;
y=(string[count+1] - '0') + x;
sum += y;
count++;
}
printf("Sum of string in two digit array is =%d\n",sum);
}
so basically if i have 123 the program does 12+(30-48), instead of 12+3. Ive been sitting on it for a while, and cant figure out how to fix that issue, any tips or advice would be welcomed.
(Strings like 1234 or 4567 will do 12+34 and 45+67)
#include <stdio.h>
#include <ctype.h>
int main(void){
char string[1000];
char digits[3] = {0};
int i, j, x, sum = 0;
printf("Enter the string containing both digits and alphabet\n");
scanf("%999s", string);
for(j = i = 0; string[i]; ++i){
if(isdigit(string[i])){
digits[j++] = string[i];
if(j==2){
sscanf(digits, "%d", &x);
sum += x;
j = 0;
}
}
}
if(j==1){
digits[j] = 0;
sscanf(digits, "%d", &x);
sum += x;
}
printf("Sum of string in two digit array is = %d\n", sum);
return 0;
}
Related
(Purpose of the code is write in the title) my code work only if i put the same number once and in the end like - 123455 but if i write 12345566 is dosent work or 11234 it dosent wort to someone know why? i have been trying for a few days and i faild agine and agine.
while(num)
{
dig = num % 10 // dig is the digit in the number
num /= 10 // num is the number the user enter
while(num2) // num2 = num
{
num2 /= 10
dig2 = num2 % 10 // dig2 is is the one digit next to dig
num2 /= 10
if(dig2 == dig) // here I check if I got the same digit twice to
// not include him
{
dig2 = 0
dig = 0
}
}
sum = sum + dig + hold
}
printf("%d", sum)
Well your code's almost correct but there's are somethings wrong ,
When you declared num2 to be equal to num1 it was out of the loop so as soon as one full loop execution is done , num2 still remains to be less than zero or to be zero if it was a unsigned int, so according to the condition the second loop wont execute after its first run.
So mind adding ,
num2 = num1
inside your first loop .
Also your updating num2 twice which i think you wont need to do after the first change .
Full code which i tried
#include<stdio.h>
int main(void)
{
int num;
int num2;
int sum = 0;
int dig, dig2;
scanf_s("%d", &num);
while (num>0)
{
dig = num % 10; //dig is the digit in the number
num /= 10;
num2 = num;// num is the number the user enter
while (num2>0) // num2 = num
{
dig2 = num2 % 10; // dig2 is is the one digit next to dig
if(dig2 == dig) // here i check if i got the same digit twice to //not include him
{
dig = 0;
}
num2 /= 10;
}
sum = sum + dig ;
}
printf("%d", sum);
return 0;
}
O(n)
#include <stdio.h>
int main () {
unsigned int input = 0;
printf("Enter data : ");
scanf("%u", &input);
int sum = 0;
int dig = 0;
int check[10] = {0};
printf("Data input: %u\n", input);
while(input) {
dig = 0;
dig = input%10;
input = input/10;
if (check[dig] == 0) {
check[dig]++;
sum += dig;
}
}
printf("Sum of digits : %d\n", sum);
return 0;
}
My program uses a character array (string) for storing an integer. We convert its every character into an integer and I remove all integers repeated and I calculate the sume of integers without repetition
My code :
#include <stdio.h>
#include <stdlib.h>
int remove_occurences(int size,int arr[size])
{int s=0;
for (int i = 0; i < size; i++)
{
for(int p=i+1;p<size;p++)
{
if (arr[i]==arr[p])
{
for (int j = i+1; j < size ;j++)
{
arr[j-1] = arr[j];
}
size--;
p--;
}
}
}
for(int i=0;i<size;i++)
{
s=s+arr[i];
}
return s;
}
int main()
{
int i=0, sum=0,p=0;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
int T[strlen(n)];
while (n[i] != '\0')
{
T[p]=n[i] - '0'; // Converting character to integer and make it into the array
p++;i++;
}
printf("\nThe sum of digits of this number :%d\n",remove_occurences(strlen(n),T));
return 0;
}
Example :
Input : 1111111111 Output : 1
Input : 12345566 Output : 21
Or ,you can use this solution :
#include <stdio.h>
#include <stdbool.h>
bool Exist(int *,int,int);
int main ()
{
unsigned int n = 0;
int m=0,s=0;
printf("Add a number please :");
scanf("%u", &n);
int T[(int)floor(log10(abs(n)))+1];
// to calculate the number of digits use : (int)floor(log10(abs(n)))+1
printf("\nThe length of this number is : %d\n",(int)floor(log10(abs(n)))+1);
int p=0;
while(n!=0)
{
m=n%10;
if(Exist(T,p,m)==true)
{
T[p]=m;
p++;
}
n=n/10;
}
for(int i=0;i<p;i++)
{
s=s+T[i];
}
printf("\nSum of digits : %d\n", s);
return 0;
}
bool Exist(int *T,int k,int c)
{
for(int i=0;i<k;i++)
{
if(T[i]==c)
{
return false;
}
}
return true;
}
Taking in input a number and then put every digit into an array, I have, converted it into a string so that I can put it into an array, but then when I use the cast to remake it a int i get the ascii number..
#include <stdio.h>
#include <stdlib.h>
int main(){
char num_str[64] = {0};
int num, cifra;
printf("Write a number: \n");
scanf("%d", &num);
int len = snprintf(num_str, 64, "%d", num);
printf("The length is %d\n", len);
for(int i = 0; i < len; i++) {
cifra = (int)(num_str[i]);
printf("%d \n", cifra);
}
return 0;
}
convert it from char to int
Test the character for digit and subtract '0'.
for(int i = 0; i < len; i++) {
int cifra = num_str[i];
if (cifra >= '0' && cifra <= '9') printf("%d\n", cifra - '0');
else printf("%c\n", cifra); // such as '-'
}
I am trying to write a function to divide a string in half but after the initial input it does not output anything. My goal is to scan a year and save the first two number and the last two numbers. This is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
// Function to print n equal parts of str
void divideString(char *str, int n) {
int str_size = strlen(str);
int i;
int part_size;
if (str_size % n != 0) {
printf("Invalid Input: String size");
printf(" is not divisible by n");
return;
}
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
}
int main() {
char year_number;
scan_year2();
char str = year_number;
divideString(str, 2);
getchar();
return 0;
}
Assuming that a year is at least a 3-digit number, the best way to treat it is to treat it as a number, not as a string:
...
int year;
scanf("%d", &year);
int first = year / 100;
int last = year % 100;
printf("%d %d\n", first, last);
...
dont ignore compiler warnings, it must be complaining at you about this
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
you try to return twice.
Also
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
is not going to give you the correct output. YOu are outputing the string each time. IE if str = "1923" then you will get
1923923
232
You should do
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%c", str[i]);
}
to only output one char at a time
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)...
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