Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there any possibilities to read and add two or three different integers by using single variable ( int a ) in C language?
I didn't want to use array
I'm not sure I'm getting you, but for example, if you want to add 2 16 bits integers with a single 32bit integer, you could do
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
uint32_t a;
printf("Enter number 1: ");
scanf("%hd", (uint16_t *)(&a));
printf("Enter number 2: ");
scanf("%hd", ((uint16_t *)(&a))+1);
printf("%X\n", a);
printf("Sum = %"PRIu32"\n", (uint32_t)(*(uint16_t *)(&a)) + *(((uint16_t *)(&a)) + 1));
return 0;
}
The logic is to think about variable equals to arrays of bytes, and that's it.
This implementation still have problems that are well explained HERE
No. Every time you you atribute a new value to the same variable it replaces the old one. If you don't want to use an array and it's a simple code to add numbers, just declare three variables and atribute each value to one of them.
I do not know if you would like this, but another way you can do this will be to accept inputs like you punch in calculators, and parse to int before applying the operations on them.
Something like this
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer[256];
char * pch;
printf("input your numbers in this format ${number1}+${number2}...: ");
fgets (buffer, 256, stdin);
int sum = 0;
pch = strtok (buffer, "+");
while (pch != NULL)
{
sum += atoi (pch);
pch = strtok (NULL, "+");
}
printf("the sum is %\n", sum);
return 0;
}
so, run it and input 2+2+2 and it does the calculation for you. thanks
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I just started C programming , My code doesn't work properly . can you help me?
This is my code :
#include <stdio.h>
int main(){
int n,sum=0,a;
scanf("%d", &n);
while (n!=0)
{ a=n%10;
sum=sum+a;
n=n/10;
}
printf("%d",&sum);
return 0;
}
You should remove "&" from your printf statement. In C, using & before a variable name means you are referencing that variable's address location. When printing, placing %d indicates the variable you will pass into the print statement will be a number in decimal format, and the return type of &sum does not match this.
If you replace &sum with sum, you will be properly referencing the value of sum instead of its address, which matches the expected type for %d. Replacing your printf statement will give you this code:
#include <stdio.h>
int main(){
int n,sum=0,a;
scanf("%d", &n);
while (n!=0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("Sum of digits: %d", sum);
return 0;
}
You are not supposed to use & before sum in your printf. We use & in scanf in order to change change a variable. But by using printf, you are just trying to show the variable's value, not its address.
So all you need to do is to omit the & before sum in you printf.
This is how the last part of your code should look like:
printf("%d", sum);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main ()
{
FILE *fp;
int r, i;
char fp_string [600] = "num1000.bin";
fp = fopen(fp_string, "rb");
for (i=0;i<1000;i++)
{
fread(&r, sizeof(int), 1, fp);
printf("%d, ", r);
}
fclose(fp);
getch();
return 0;
}
This code currently reads and displays a binary file called num1000.bin, which contains 1000 random numbers. This code uses a for loop. How can I perform the exact same task but instead using an array?
To define an array:
int r[1000];
To read 1000 files from your file, use fread:
fread(r, sizeof(int), 1000, fp);
As you can see in the description of the fread function, one of its parameters specifies how many elements to read. Change it from 1 to 1000.
To display your numbers, you still need a loop.
for (i=0;i<1000;i++)
{
printf("%d, ", r[i]);
}
Notice how it's now r[i] - because r is now an array that contains 1000 numbers, and not just one.
Firslty you need to know the format of the random numbers. Presumably they are in native int format, but you need to check, especially since they are rnadom and so no commonsense testing is possible.
If you know that the number is exactly 1000, you can read in using fread
int r[1000];
fread(r, sizeof(int), 1000, fp);
But this is a bad habit. The data might end early. The format might be endian-reversed from native, or 16 or 64 bit instead of 32. You really need to get into the habit of reading binary data portably.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a function that gets input in the form of int1, int2, ..., intn.
I neeed to store the values of these integers in an array. A separate function is used to get the number of integers to be read. How can I make the two functions work?
If it's not clear, it's something like this:
function1 gets an integer to get the number of input to be read. Then the function2 will read that input plus one but the input must be in a single line and must be separated by a comma and/or a white space.
Function1 gets, for example 5. function2 will want to read input like: 3, 21, 5, 1, 5, 2 and store it into a separate array for later use.
Can anyone help? Thanks. I thought of using loops but I remembered that the input must be in one line. Maybe scanf? With [^,]? But how do I make it work with the first function?
Try this:
#include <stdio.h>
void getInput(int sizeOfInput, int arr[]) {
int i = 0;
printf("IN");
for(; i < sizeOfInput - 1; ++i) {
scanf("%d, ", &arr[i]);
}
scanf("%d", &arr[i]);
printf("OUT");
}
main(){
int sizeOfInput = 0;
printf("Enter how many numbers do you want to enter?");
scanf("%d", &sizeOfInput);
int arr[sizeOfInput];
getInput(sizeOfInput, arr);
}
Sorry I am lazy but for you to learn it would be the best to figure out what this code does before you use it, that is also a reason why I did not comment it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get a duration of time into minutes from a string. I am given a string like this: "1:50". And I need to extract the minutes and seconds from this strings into int variables and then return the duration in minutes. So I wrote this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
int main()
{
char time[6]="01:30";
int duration=0, minutes=0, seconds=0;
int buffermin[3];
int buffersec[3];
int i=0;
while(i<2)
{
sscanf(time[i],"%d%d",&buffermin[i]); //Get the first two characters in the string and store them in a intger array
i++;
}
i=3;
while(i<5)
{
sscanf(time[i],"%d%d",&buffersec[i]); //Get the last two characters in the string and store them in a integer array
i++;
}
printf("%d %d %d %d", buffermin[0], buffermin[1], buffersec[0], buffersec[1]);
getch();
minutes=(buffermin[0]*10)+buffermin[1]; //Put values in array to one variable
seconds=(buffersec[0]*10)+buffersec[1]; //Same as above
seconds=seconds/60; //Turn the number of seconds to minutes
duration=seconds+minutes; //Get total duration
printf("The total duration is: %d\n",duration); //Output total duration
getch();
exit(0);
}
Why is this not working and how could I fix this. Any examples would be really very appreciated. If you have the time to explain how the example works, please do so. Still poor at programming as you can see.
You should really learn how to use sscanf properly. Basically, what you want to achieve is this:
#include <stdio.h>
int main() {
char time[] = "01:27";
int minutes;
int seconds;
// Must be double, not integer, otherwise decimal digits will be truncated
double duration;
// String has format "integer:integer"
int parsed = sscanf(time, "%d:%d", &minutes, &seconds);
// Check if input was valid
if (parsed < 2) {
// String had wrong format, less than 2 integers parsed
printf("Error: bad time format");
return 1;
}
// Convert to minutes (mind the floating point division)
duration = (seconds / 60.0) + minutes;
printf("Duration: %.2f minutes\n", duration);
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have got a program to do as my homework. the program is simple. it asks to reverse the digits entered by the user and then print it using while loop. the problem arises when the user enters a number starting with zeroes.
For example:
Enter the number: 0089
The reversed number is : 9800
This is how the output should be. instead i get "98" as the answer.
and thanks in advance.
When asked to do someone else's homework, I like to devise an obtuse and compact way to do it.
void reverseNumber(void)
{
char c;
((c=getchar()) == '\n')? 0 : reverseNumber(), putchar(c);
}
Rather than reading the 0089 input as a numeric value, read it as a character array. This way the zeros won't be removed.
Read the numbers as a string.
And then use atoi() (stdlib.h) to make an integer number out if the string:
/* int atoi (const char *) */
Here is working code that makes exactly what your question requires:
// input: 0321
// output: 1230
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80] = {0}, temp_str[80] = {0};
int num, i, length = 0, temp_length = 0;
printf("Enter a reversed number (e.g. 0089): ");
scanf("%s", str);
length = strlen(str);
temp_length = length;
printf("string_length: %d\n", length);
for ( i = 0; i < length; i++ ) {
temp_str[i] = str[temp_length - 1];
/* The string length is 4 but arrays are [0][1][2][3] (you see?),
so we need to decrement `temp_length` (minus 1) */
temp_length--;
}
printf("temp_str: %s\n", temp_str);
num = atoi(temp_str);
printf("num: %d\n", num);
return 0;
}