Why is the output of my C program incorrect? - c

This is my code in C that reads data from input:
#include<string.h>
#define MAX 3
char a[MAX];
char b[MAX];
void ReadFirstNumber();
void ReadSecondNumber();
int lb,la=0;
void main()
{
ReadFirstNumber();
ReadSecondNumber();
printf("\n First Number > %d %d %d \n",a[0],a[1],a[2]);
printf(" Second Number > %d %d %d \n",b[0],b[1],b[2]);
}
void ReadFirstNumber()
{
int i=0;
printf("Enter the first number:");
scanf("%s", a);
la=strlen(a)-1;
for(i=0;i<=la;i++)
{
a[i] = a[i] -48;
}
}
void ReadSecondNumber()
{
int j=0;
printf("Enter the Second number:");
scanf("%s", b);
lb=strlen(b)-1;
for(j=0;j<=lb;j++)
{
b[j] = b[j] -48;
}
}
input first number example: 123
input second number example: 456 or any 3-digit number
//output
First Number **0**23
Second Number 456
The output for first number is 023
The first character is Zero! but the output for second number is ok.
When I comment out second function //ReadSecondNumber(); it worked perfectly!

You failed to allow enough space for the null terminator char that scanf("%s",...) writes at the end of 'strings'. Increase the value of the MAX #define. You may as well put in something sanely larger, eg 32.

Related

Inserting spaces between a 5 digit number

I have started an intro to programming course that uses the C language and we have an assignment to make a program that takes a 5 digit number from the user such as 12345 and it prints it out as 1 2 3 4 5.
I tried to google around for help but all the answers given used code way too complicated for my understanding considering the course just started and we have only learned printf and scanf, if and switch statements and while and for loops.
I tried putting all the numbers given into separate int variables which made the program stop and then tried to put them into chars but the testing program said it was wrong since we are supposed to use int.
Is there a simple way to do this?
EDIT:
What I have tried:
#include <stdio.h>
int main(void) {
int num1,
num2,
num3,
num4,
num5;
printf("Give 5 digit number > ");
scanf("%d%d%d%d%d", &num1, &num2, &num3, &num4, &num5);
printf("Seperated number is %d %d %d %d %d", num1, num2, num3, num4, num5);
return (0);
}
Also tried that code but with char variable type but that wasn't allowed it has to be int.
The testing program gives an expected output which for 00001 is Given number 1 seperated is 0 0 0 0 1 or for -12321 is Given number -12321 seperated is -1 -2 -3 -2 -1
You can read user input into a char array using scanf.
Then using for loop you can loop through each char (1,2,3,4,5)
Use printf in the loop to print from array and a space. printf("%c ", input_from_user[i]);
I suppose the point here is understanding how C stores things. You're reading in characters (that is a set of 8-byte values that are commonly displayed as letters) and converting each one to an integer (commonly a 32-bit value that stores a number)
So you want to read the input using scanf to get a character string of your 5 digits, then use a for loop to go over each one, reading a single character from the string and converting it into an integer variable. then printf that variable plus a space, and move on to repeat the next digit.
If you read the digits in one by one then its even easier as you only need the for loop to read, convert, and print each digit as its read.
According to the question, you would be given a number of 5 digits and then you have to print the digits of that number as well.
So, in your program, you have taken five digits individually as input, to me it seems wrong. I am giving my solution below:
#include <stdio.h>
int main(void)
{
int num,idx=0,i=0;
int arr[5]; // for storing the five digits;
scanf("%d",&num);
while(num){ //loop will terminate when the num = 0
int digit = num%10;
num = num/10;
arr[idx] = digit;
idx++;
}
//Printing from the last, as the digit are stored in reverse order.
for(int i=4;i>=0;i--){
printf("%d ",arr[i]);
}
return 0;
}
I don't really understand the purpose of this exercise. If you are learning C, the last function you should learn is scanf. It boggles the mind that so many people teach it early. Try very hard not to use scanf at all until you understand the language well enough to realize that you probably never need it. That said, I suppose the point of the exercise is to do something like:
#include <stdio.h>
int
main(void)
{
unsigned num;
char buf[6];
printf("Give 5 digit number > ");
if( scanf("%u", &num) != 1 || num > 99999 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
printf("Separated number is");
snprintf(buf, sizeof buf, "%d", num);
for( int i = 0; buf[i]; i++ ) {
printf(" %c", buf[i]);
}
putchar('\n');
return 0;
}
Although likely beyond OP's stage, code can use recursion to print the value from most significant to least.
#include <stdio.h>
void print_digit(int n, int depth) {
if (depth > 1) print_digit(n/10, depth - 1); // print "left" digits first
printf(" %d", n%10);
}
void print_5(int n) {
// To do: checking for correct spelling
printf("Given number %d seperated", n); // or separated
print_digit(n, 5);
printf("\n");
}
int main(void)
{
print_5(1);
print_5(-12321);
return 0;
}
Output
Given number 1 seperated 0 0 0 0 1
Given number -12321 seperated -1 -2 -3 -2 -1
You could use your approach by limiting the number of bytes you read for each number:
#include <stdio.h>
int main(void) {
int num1, num2, num3, num4, num5;
printf("Give 5 digit number > ");
if (scanf("%1d%1d%1d%1d%1d", &num1, &num2,&num3, &num4, &num5) == 5) {
printf("Separated number is %d %d %d %d %d\n", num1, num2, num3, num4, num5);
}
return 0;
}
Note however that this is probably not what you are expected to do. You should instead read a single number and decompose it into its five digits:
#include <stdio.h>
int main(void) {
int num;
printf("Give 5 digit number > ");
if (scanf("%d", &num) == 1 && num >= 10000 && num <= 99999) {
printf("Separated number is %d %d %d %d %d\n",
num / 10000, num / 1000 % 10, num / 100 % 10, num / 10 % 10, num % 10);
}
return 0;
}

How To show original value of a variable after variable has been changed

So I'm having a problem about showing what my original variable value is after changing it in the code.
#include <stdio.h>
int main(){
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
while (n!=0){
n/=10;
count++;
}
printf("your number %d has %d digits", n, count);
return 0;
}
Example input:123
Output of this code "your number 0 has 3 digits"
I want to know how to be able to refer the variable "n" in the printf to the original value of '123' so the output will be "your number 123 has 3 digits"
I would recommend that you use a separate variable to save your value or count with a different variable.
This code would look something like this:
#include <stdio.h>
int main()
{
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
int buffer = n
while (buffer!=0)
{
buffer/=10;
count++;
}
printf("your number %d has %d digits", n, count);
return 0;
}
This way you save your variable in your code and you only used a buffer and not the actual value n.
You can keep a copy of the original variable and use that copy of the variable while printing.
You can do this:
int main(){
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
printf("your number %d has ", n);
while (n!=0){
n/=10;
count++;
}
printf("%d digits", count);
return 0;
}
Of course, you may have to do some error checks..

How to pass arrays into functions in C ( on Fedora )?

Since I am a beginner have been practicing passing arrays as parameters to functions. Could someone explain why this program I wrote works fine on codeblox, but doesn't work in Fedora terminal (on Fedora it doesn't work for any number of scores). I'm using the GCC compiler.
#include<stdio.h>
int num,scores[]={},count,max,sum;
void input(int scores[]);
int findmax(int scores[]);
int findsum(int scores[]);
void display(int max,int sum);
int main()
{
printf("Enter number of scores\n");
scanf("%d",&num);
input(scores);
max=findmax(scores);
sum=findsum(scores);
display(max,sum);
return 0;
}
void input(int scores[])
{
for(count=0; count<num; count ++)
{
printf("Enter score #%d:\n",count);
scanf("%d",&scores[count]);
}
}
int findmax(int scores[])
{
for(count=0; count<num ; count ++)
{
if(scores[count]>max)
{
max=scores[count];
}
}
return max;
}
int findsum(int scores[])
{ sum=0;
for(count=0; count<num ; count++ )
{
sum=sum+scores[count];
}
return sum;
}
void display(int max,int sum)
{
printf("The max score is :%d\nThe total score is:%d\n",max,sum);
}
You should avoid using global variables unless they are absolutely required. None are required here. All values should be declared local to main and should be passed to each function as a parameter, as required.
You must validate ALL input by, at minimum, checking the return of scanf (or whatever input function you are using). If a user simply pressed Enter (generating a '\n') or enters words instead of numbers causing the conversion to fail, you are dead in the water and may well be watching an infinite loop scroll by until you kill the process. (a cat might step on the keyboard, etc.)
When using the scanf family of functions, if a failure occurs, you must account for any characters left in the input buffer (e.g. stdin with scanf). If scanf is called within a loop, you risk an infinite loop where the conversion fails, leaving the same characters in the input buffer only to be read again, and fail, over-and-over again.
If you do not validate your input, you can have no confidence that you are processing a valid input from that point forward, and may in fact be well off into Undefined Behavior. The scanf family of functions returns the number of valid conversions based on the number of format-specifiers contained within the format-string. So with "%d", you have one format-specifier (e.g. %d), so upon successful conversion the return will be 1 (you should also check for EOF if the user manually cancels input with Ctrl + d, or Ctrl + z on windoze -- which is left to you)
Putting those pieces together, you could do something like the following:
#include <stdio.h>
#include <limits.h> /* for INT_MIN */
#define MAX 512
void input (int *scores, int num);
int findmax (int *scores, int num);
int findsum (int *scores, int num);
void display (int max, int sum);
int main (void)
{
int num, scores[MAX] = { 0 }, max, sum;
printf ("Enter number of scores: ");
if (scanf ("%d", &num) != 1) { /* VALIDATE ALL input */
fprintf (stderr, "error: invalid integer input.\n");
return 1;
}
input (scores, num);
max = findmax (scores, num);
sum = findsum (scores, num);
display (max, sum);
return 0;
}
void input (int *scores, int num)
{
int count = 0;
while (count < MAX && count < num) { /* always protect array bounds */
printf ("Enter score [%d]: ", count);
while (scanf ("%d", &scores[count]) != 1) { /* VALIDATE input */
fprintf (stderr, "error: invalid input, try again.\n");
/* remove invalid chars from input buffer */
for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
goto badval;
}
count++;
badval:;
}
}
int findmax (int *scores, int num)
{
int max = INT_MIN, count;
for (count = 0; count < num; count++)
if (scores[count] > max)
max = scores[count];
return max;
}
int findsum (int *scores, int num)
{
int sum = 0, count;
for (count = 0; count < num; count++)
sum = sum + scores[count];
return sum;
}
void display (int max, int sum)
{
printf ("\nThe max score is :%d\nThe total score is:%d\n", max, sum);
}
Example Use/Output
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: 2
The max score is :9
The total score is:29
With Error Correction
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: foo
error: invalid input, try again.
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: bar
error: invalid input, try again.
Enter score [4]: 2
The max score is :9
The total score is:29
Leave a comment if you have further questions.

How to get multiple inputs in one line in C?

I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Read in the whole line, then use a loop to parse out what you need.
To get you started:
1) Here is the manual page for getline(3):
http://man7.org/linux/man-pages/man3/getline.3.html
2) Some alternatves to getline:
How to read a line from the console in C?
3) Consider compressing spaces:
How do I replace multiple spaces with a single space?
4) Use a loop for parsing. You might consider tokenizing:
Tokenizing strings in C
5) Be careful and remember that your user could enter anything.
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
/*
_______________This program is in C Programming Language_______________
We have to directly enter all the elements in one line giving spaces between them. Compiler will automatically ends the for loop I have used and assign the value to their respective variables or array indexes. Below program and output will give you better understanding.
*/
#include <stdio.h>
int main()
{
//taking no of inputs from user
int len;
printf("Enter the number of inputs you want to enter : ");
scanf("%d", &len);
int i;
//defined an array for storing multiple outputs
int arr[100];
//included a printf statement for better understanding of end user
printf("Enter the inputs here by giving space after each input : ");
/*here is the important lines of codess for taking multiple inputs on one line*/
for (i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
printf("Your entered elements is : ");
for (i=0;i<len;i++)
{
printf("%d ", arr[i]);
}
}
/*
OUTPUT :
Enter the number of inputs you want to enter : 5
5 5 5 8 7
Your entered elements is : 5 5 5 8 7
*/

How to correctly handle scanf()

I have to take input in the following format
S1 S2 S3
where S1 is a character and S2,S3 are integers
for example
3
A 123 452
D 450 53
B 330 672
(where the '3' represents the number of queries)
Now I've written the following code for it :
while(i<=Q){
scanf("%c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
However, for the above shown three values I am getting the following output
0 755130840
A 123 452
123 452
with an extra line at the top and that large value (here 755130840) changing every time.
Where am I going wrong?? I even tried scanning the 3 values individually and flushing the input stream before each scan statement. However, It doesn't help either.
Given the two blank lines, I believe the newline ('\n') is being stored in some variable.How do I handle it?
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading ch.
scanf with blank skips white space (including newlines) and reads the next character that is not white space.
Here is a code , this would be working fine.
#include <stdio.h>
int main(void) {
// your code goes here
int i =0;
int Q = 2;
char ch;
int index;
int num;
while(i<=Q){
scanf(" %c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
return 0;
}
do you want something like this?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, count, numone, numtwo;
char charip;
printf("Enter numbr of elem:\t");
scanf("%d", &num);
if (num < 0)
{
printf("Enter positive value!!!!!\n");
exit (-1);
}
count = 0;
while (count < num)
{
getchar();
scanf ("%c %d %d", &charip, &numone, &numtwo) ;
printf("%c %d %d\n", charip, numone, numtwo);
count++;
}
return 0;
}

Resources