I need my code to print out
Input the number of values: Input the values between 0 and 9 (separated by space):
your histogram:
0-3
1-2
2-0
etc.
but it looks nothing like that? help
#include<stdio.h>
void printStars(int n){
int i;
for(i = 0;i<n;i++){
printf("*");
}
printf("\n");
}
int main() {
int i,n = 10;
int input[100];
int hist[10] = {0};
printf("Input the amount of values: ");
scanf("%d",&n);
printf("Input the values between 0 and 9 (separated by space): ");
for(i = 0;i<n;i++){
scanf("%d",&input[i]);
}
for(i = 0;i<n;i++){
hist[input[i]]++;
}
printf("\n\nYour histogram: ");
for(i = 0;i<10;i++){
printf("%d - %d\n",i,hist[i]);
}
return 0;
}
I'm assuming the printStars(int n) method is supposed to replace count of each number,
e.g. instead of 0 - 3 you would see 0 - * * *
If this is the case, you will want to change the for loop on line 25 to this:
for(i = 0; i < 10; i++){
printf("%d - ",i);
printStars(hist[i]);
}
Also, on line 24, you need an additional \n at the end of the printf to put your 0-count for the histogram on its own line: printf("\n\nYour Histogram: \n");
Don't forget to make sure your input is within bounds as well, as you never check if int n is within bounds of input[]. Speaking of this, why is n instantiated to 10, then immediately scanned into for input without use of n = 10?
If you aren't seeing any output on run, try typing input immediately. It's possible that requesting input is clearing the current line printed to.
printf("Input the amount of values: ");
scanf("%d",&n);
In this case, since there is no \n at the end of the printf and a scanf is immediately called, the input request might be clearing the output line and requesting input. Adding a \n to the end of printf might correct this, if it is the problem you're having.
Other than this, there doesn't seem to be any major problems.
your code is working. What format do you get and what format do you expect ? Personally, I have the
0-3
1-2
2-0
format
Related
I am trying to code a program that asks the user for the # of rows and columns and generates a 2d array (a matrix) corresponding to their input. I then ask for a second matrix (same dimensions), then I do some math on the 2 matrices. I'm stuck on how to use the scanf function to get the user-inputted matrix. According to the guidelines, the user input will be in the shape of the matrix itself, ex if it is a 2x2 matrix the user enters:
12 10 (then on the next line)
10 10
How do I use the scanf function appropriately to copy this matrix into the 2d array that I've created? I know that you can do scanf("%d %d %d", &int1, &int2, &int3), but I don't know if this will work for a user-determined matrix, since the length could be 2, 10, even a 100 (which is max length for this problem).
#include <stdio.h>
int main(void) {
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
/*User enters matrix in the form:
12 10
10 10
*/
printf("Enter Matrix A\n");
for(int i=0; i<sizeof(matrixA); i++){
for(int j=0; j<sizeof(matrixA[i]);i++){
scanf("%d ",&matrixA[i][j]);
}
}
//to see if scanf worked
for (int i = 0; i<sizeof(matrixA); i++) {
for(int j=0; j<sizeof(matrixA[i]);i++) {
matrixA[i][j] = '.';
printf("%c ",matrixA[i][j]);
}
printf("\n");
}
int matrixB[r][c];
printf("Enter Matrix B\n");
return 0;
}
You are right that
scanf( "%d %d %d", &int1, &int2, &int3 );
will only work if the number of parameters is fixed at compile-time. It cannot be changed at run-time.
Your idea of calling
scanf("%d ",&matrixA[i][j]);
in a loop instead is correct, in principle. However, you should not have a space character in the format string, as this will cause scanf to continue to read input from the input stream, and it will only return after it has encountered a non-whitespace character. This is usually not what you want.
Also, the line
for(int i=0; i<sizeof(matrixA); i++){
is wrong, because sizeof(matrixA) is the size of the array in bytes. Since you instead want to get the number of elements in the outer array, you could write sizeof matrixA / sizeof *matrixA instead. (The parentheses are only necessary when referring to types, not variables.) However, in this case, it would be easier to simply use r instead.
The line
for(int j=0; j<sizeof(matrixA[i]);i++){
is wrong. You probably intended to write j++ instead of i++.
Also, when printing variables of type int with printf, you should usually use %d instead of %c, because otherwise the value may be truncated if the value is higher than 127.
It is unclear what the line
matrixA[i][j] = '.';
is supposed to accomplish, as this will overwrite the previous input of scanf (assuming that you fix your loop as described above).
After fixing all of the issues mentioned above, your code should look like this:
#include <stdio.h>
int main(void)
{
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
printf("Enter Matrix A:\n");
for ( int i=0; i < r; i++ )
for( int j=0; j < c; j++ )
scanf( "%d", &matrixA[i][j] );
//to see if scanf worked
printf( "Input complete, the array contents are:\n" );
for ( int i=0; i < r; i++ )
{
for( int j=0; j < c; j++ )
printf( "%d ",matrixA[i][j] );
printf( "\n" );
}
return 0;
}
This program has the following behavior:
Please enter the number of rows : 4
Please enter the number of columns : 4
Enter Matrix A:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input complete, the array contents are:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
POSIX-specific answer
Well, you don't.
There are two ways to get that done:
Slice stdin into rows by the '\n' character n times; later slice every row in n columns by ' ' the whitespace. getline and strtok come in handy here.
The other approach is more efficient and as usual more complicated: rather than slicing into rows first, you iterative cut-off cols, counting them, and when count == n comes true, you expect '\n' to be there thus ending another line. I wouldn't suggest this approach.
So roughly your codes looks something like:
ssize_t nread;
for (sizet_t i = 0; i < n; i++) {
char *line = NULL;
if ((nread = getline(&line, &len, stream)) != -1) {
fprintf(stderr, "Bad format: %il-th line expected.", i + );
exit(EXIT_FAILURE);
}
char* token = strtok(line, " ");
for (size_t ii = 1 /* because you've already cut-off the first token */; i < n; ii++) {
token = strtok(NULL, " ");
}
}
Of course, you have to parse your char * tokens, but that is something I leave to you as an exercise. It also quite sloppy and does not do any sort of validation a production code is expected to do.
enter image description here
how can I do this using scanf funtion ranging form -1000 to 1000 ?
just %d numbers
Try dooing a loop with a scanf and a printf inside, like this:
int num = 0;
for(int i = 0; i < 5; i++){
scanf("%d", &num);
printf("%d", num);
}
You just need to change the 5 to the number of iterations you need.
I am attaching the code for the same.Its working fine.But once i enter a number less than the previous one it stops giving desired output.Any help/suggestion shall be greatly appreciated.
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
In your outer while loop, you're never resetting the value of the variable i back to 1, or j back to 0. That is why subsequent loops will produce an incorrect sum.
There are a smattering of bugs in this code, including:
Comparison to uninitialized value of of ch in the initial while expression.
Failing to reset i and j for each outer-loop iteration
Failing to test for data-read success in either scanf call to ensure proper input.
The continuation scanf("%s", &ch) is simply wrong for a single character with skipped whitespace (which you must do to avoid reading the newline after your list integer input). Unless EOF or an error state is reached, what you have now is guaranteed to invoke undefined behavior, as a string-read of at least one character requires at least two for storage (the character, and a subsequent terminator).
Addressing all of those:
#include <stdio.h>
int main()
{
char ch;
do
{
int n;
printf("Enter the number upto which you want the sum of \n \n");
if (scanf("%d", &n) != 1) // See (3)
break;
int j = 0; // See (2)
for (int i = 1; i <= n; ++i) // See (2)
j += i;
printf("%d \n", j);
printf("Do it with another number? Y/N \n \n");
if (scanf(" %c", &ch) != 1) // See (3) and (4)
break;
} while (ch != 'n' && ch != 'N'); // See (1)
return 0;
}
Everything here is self-explanatory when referred to the previous bug punch list, save for maybe the format string for reading the single character. You mentioned in comments that you tried %c but it skipped to another loop iteration. That's because you didn't have the leading whitespace " %c" that tells scanf to skip white space before extracting the next argument. With that, it should work as desired.
You need to reset i and j for every n.
i = 1;j=0;
while(i<=n)
{
Also your format specifer is wrong. For char, it should be %c and not %s
scanf("%c",&ch);
The simplest solution is to set i to 0 at the outer while:
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
Note that I have changed <= to < for your inner while, since you do not want to increment the value if the same n is inputted one after the other.
#include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%c",&ch);//this is a char not a string
}
return 0;
}
Due to the i is not initializing to 1 when the loop is coming for the second time there it is not going inside the loop and printing the previous value .
before each sentence it needs to say the number of the sentence im writing. starting the count from one.
what i mean is:
How many sentences you want to enter [1-5]?
2
sentence 1: write what you want
sentence 2: here as long as its less then 50 letters
my problem is that i dont know how to limit the number of letters, without needing to insert them all.
if i write
for(i=0; i<50; i++)
i will need to enter all the 50 letters, but if i want i need to be able to write even only 1.
so that is what i have done so far: (note that i dont need to ask the user how many letters he wants to enter)
char text[5][50]={0};
int x=0, i=0, n=0, m=0;
printf("How many sentences you want to enter [1-5]?\n");
scanf("%d", &n);
printf("how many letters [1-50]?\n");
scanf("%d", &m);
for (x=1; x<=n; x++)// will print max of 5 sentences
{
printf("Sentence %d: \n", x);
for(i=0; i<m; i++)// will print max of 50 letters
{
scanf(" %c", &text[x][i]);
}
}
thanks a lot for the help!
for(i=0;i<n;i++)
{
if(fgets(text,50,stdin) != NULL) /* Read just 50 character */
{
// Do your stuff
}
}
PS: fgets() comes with a newline character
There is still an error.
for (x=1; x<=n; x++)
will cause an indexing error when x==5. Always maintain your indexing to suit the language. Use
for (x=0; x<n; x++)
Add 1 for human information
printf("Sentence %d: \n", x + 1);
And as #cmatsuoka wrote, the array should be
char text[5][51]={0};
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.