Put a number in array, and convert it from char to int - c

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

Related

Can we scanf an array?

I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);

C, dividing a string in half

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

Find missing lower-case letters that are not in a series of words

As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}

two-digit string addition with no number at the end

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

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