Could anyone please help me with this c program coding? [closed] - c

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

Related

Problem when I print a result of integer operation with chars in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I state that I'm a newbie of C programming. I have to solve this "easy" C exercise.
The program has in input two chars. These chars must be a numeric value between 0 and 9. I have to sum the chars and print the result. I have to repeat this until the first inserted char isn't -1. This is my implementation:
#include <stdio.h>
#define ASCII_ZERO 48
int main() {
char a, b;
while (1) {
scanf("%c %c", &a, &b);
int x = (int)a - ASCII_ZERO;
int y = (int)b - ASCII_ZERO;
if (x == -1) break;
int z = x + y;
char ris = z;
printf("ris: %d\n", ris);
}
exit(0);
}
When I run this code, I got this:
1 2
ris: 3
3 4
ris: -35
ris: -12
Why I get "ris" two times when I insert 3 and 4?
This works
...
char a, b, c;
while (1) {
scanf("%c %c%c", &a, &b, &c);
...
printf("ris: %d\n", ris);
}
return 0;
}
I will not comment on code. But what is happening is that a is reading '\n' when the loop runs again : which you have pressed. As you are reading characters, '\n' and white spaces are also read. I just read \n into a dummy variable c which is not used.
All this said, I suggest that you use fgets

C Program stopped working after using scanf instead of var=0 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I have this code:
#include <stdio.h>
#include <stdlib.h>
int functie ( int v[], int nr, int z)
{
int i,count;
scanf("%d", &z);
for(i=0;i<nr;i++) {
if(z==v[i]) {
count=count+1;
}
}
return z;
}
int main()
{
int i,nr,z;
fscanf("%d", &z);
FILE *f;
FILE *g;
f=fopen("data-in.txt", "r");
fscanf(f,"%d",&nr);
int *v=malloc(nr*sizeof(int));
for(i=0;i<nr;i++) {
fscanf(f,"%d",&v[i]);
}
g=fopen("data-out.txt", "w");
fprintf(g,"%d %d", functie(v,nr,z));
fclose(f);
fclose(g);
free(v);
}
and before I had int z=0; instead of trying to scanf my var z.
When I run this I get a stopped working error.
I have an array with numbers (integers) read from file, first line is the number of elements and second line the elements.
I need a var lets say z to check how many times an element appears in vector (check if scanned number z is equal to an element and +1 count )
example:
in file
4 (cuz I have 4 elements )
1 2 3 3 ( my elements )
than scan z as 3
z==3 true
count=1
again
count=2
Two issues here, both in main. First:
fscanf("%d", &z);
This function expects a FILE * for the first argument, which you didn't specify. Presumably you wanted to read from the console instead, so use scanf:
scanf("%d", &z);
Second issue:
fprintf(g,"%d %d", functie(v,nr,z));
Your format string is expecting two integer arguments, but you're only passing in one. Get rid of the extra format specifier:
fprintf(g,"%d", functie(v,nr,z));
fscanf will not be delimited by newlines. Best thing to do is eat through file a line at a time with fgets. So, add a line buffer to the top of main:
char line[16]; // assuming integers will actually be small
After opening your file as above with 'f':
if (fgets(line, sizeof(line), f))
{
int count = atoi(line);
int *v = (int *) malloc(count * sizeof(int));
for (int i = 0; i < count && fgets(line, sizeof(line), f); ++i)
{
v[i] = atoi(line);
}
}
You should absolutely add error checking to the above, which is minimal and for concept only (e.g. guard against bad input, buffer overflow, exceptions, count being wrong leaving you uninitialized integers at the end of the array, etc.) as this will only work if your input file is perfect. Note that 16 is generally a ridiculously small length for a line buffer. Also only do your logic against your vector if (a) the file opens, and (b) passes the first test, which is an integral number of entries.

Primes in C: RunTime Error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.

Tokenise a String in C programming [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm new to C programming and I know there have been other explanations on how to split a string into words but none of them seem similar to my program. I'm having difficulty finding the errors in my program:
#include <stdio.h>
#include <stdlib.h>
int tokenise(char str[], int start, char result[]) {
if (str[start] == "/o") {
return -1;
} else {
result = str[start];
}
}
int main() {
const int MAX_STRING = 256;
char buffer[MAX_STRING];
fgets(buffer, MAX_STRING, stdin);
char result[256];
int start;
start = tokenise(buffer, 0, result);
while ( start != -1 ) {
printf("%s\n", result);
start = tokenise(buffer, start, result);
}
}
In your function tokenise -
if(str[start] == "/o"){
What is "/o" you compare with? It should be '\0'.
if(str[start] == '\0'){
And in else your function does not return anything , therefore , in that case UB.
You function doesn't have any loop or use recursion to iterate over array ,therefore , your logic doesn't seem to achieve anything close .
You have many problems with your code:
else {
result = str[start];
}
No return value. That is undefined behaviour.
str[start] == '\o'
Thats incorrect as you want to compare to the EOS null termination character
Do this instead:
str[start] == '\0'
Lastly, if you want your tokenise function to write into result, you need to pass a pointer to result, not the value of result.
ps: semantic errors aside, your function does nothing resembling what you want. Look into loops and their implementation.

Addition of two numbers in c [closed]

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

Resources