How to Add Space in Output - c

Size of array <=1000 and reverse a array in C programming & problem is in printing.
For example output is:
7654321
I want:
7 6 5 4 3 2 1
The first line take input about the number of elements in the array. The second prints the reverse of the array.
#include <stdio.h>
int main()
{
int k, i;
scanf("%d",&k); //no of integers in array
int a[1000]; //size given in question
for(i=0;i<=1000;i++)//accepting input
scanf("%d",&a[i]);
for(i=k-1;i>=0;i--)//for reversing string
printf("%d",a[i]);//my problem
//code
return 0;
}

Apart from your question the program is invalid.
The valid range of indices for the array declared in the program is [0, 1000).
However in this loop
for(i=0;i<=1000;i++)//accepting input
scanf("%d",&a[i]);
you are trying to access the element with the index equal to 1000 though the array does not have such an element.
If your compiler supports variable length arrays then you could declare an array with the number of elements entered by the user.
In this case the program can look like
#include <stdio.h>
int main( void )
{
size_t n;
printf( "Enter the size of an array (0 - exit): " );
if ( scanf( "%zu", &n ) == 1 && n != 0 )
{
int a[n];
for ( size_t i = 0; i < n; i++ ) scanf( "%d", &a[i] );
putchar( '\n' );
for ( size_t i = n; i != 0; i-- ) printf( "%d ", a[i-1] );
putchar( '\n' );
}
}
The program output might look like
Enter the size of an array (0 - exit): 10
9 8 7 6 5 4 3 2 1 0
Pay attention to the call of printf
printf( "%d ", a[i-1] )
^^^
It can be substituted to the following two function calls
for ( size_t i = n; i != 0; i-- )
{
printf( "%d", a[i-1] );
putchar( ' ' );
}

Related

How to get user to input number between 1-10 only

I'm writing a code that I want to make sure the User only inputs an integer between 1-10 and stores that value in a 2D array. I'm trying to use pointers to do complete this task.
#include <stdio.h>
int main()
{
//Declaration of a 2D array
int movie_Scores [8][5];
//Declaration of a pointer variable which points to the address of the 1st element
int *p;
p=&movie_Scores;
//Array of pointers to strings and initializtion
char movie_Names[][100] = {"1. Movie 1",
"2. Movie 2",
"3. Movie 3",
"4. Movie 4",
"5. Movie 5",
"6. Movie 6",
"7. Movie 7",
"8. Movie 8"
};
for(int i=0; i<5; i++)
{
printf("Judge %d, rate each movie from 1-10:\n\n", i+1);
for(int j=0;j<8;j++)
{
printf("\n%s\t:", movie_Names[j]);
scanf("%d", (p+i+(j*5)));
while(*(p+i+(j*5))<1 || *(p+i+(j*5))>10)
{
printf("Enter number between 1-10:\n");
printf("\n%s\t:", movie_Names[j]);
scanf("%d", (p+i+(j*5)));
}
}
}
}
Currently my code takes the input and directly stores it into the array without checking if the value entered is between 1-10.
Input functions do not test for valid range. (In fact, that is a known failing of scanf. See here and here for the eyes-glaze-over reasons.) You need to test the value after you get it.
int value;
if (!scanf( "%d", &value )) fooey();
if ((value < 1) or (value > 10)) fooey();
Getting input in C is actually a rather obnoxious thing to do. You can write yourself a helper function to put all the messy stuff in one spot, then you can use it elsewhere.
Also, use better variable names, and don’t introduce gratuitous variables.
for(int judge_number=0; judge_number<5; judge_number++)
{
printf("Judge %d, rate each movie from 1-10:\n", judge_number+1);
for(int movie_number=0; movie_number<8; movie_number++)
{
int rating;
for (;;)
{
printf("%s\t:", movie_Names[movie_number]);
scanf("%d", &rating);
if ((rating >= 1) and (rating <= 10)) break;
printf("Rating must be an integer in 1 to 10.\n");
}
movie_Scores[movie_number][judge_number] = rating;
}
}
EDIT: BTW, I would be remiss if I didn’t mention today’s magic numbers 5 and 8.
You should not use magic numbers. Instead, provide a named value somewhere.
#define NUMBER_OF_MOVIES 8
#define NUMBER_OF_JUDGES 5
Then you can use those identifiers anywhere you need them:
int movie_Scores [NUMBER_OF_MOVIES][NUMBER_OF_JUDGES];
And:
for (int judge_number=0; judge_number<NUMBER_OF_JUDGES; judge_number++)
Et cetera.
First, I'd write a function that reads an int and checks it against an input, returning 1 if an acceptable int was read, and 0 if one was not.
int read_int_from_range(int *n, int start, int end) {
int r = scanf("%d", n);
return r == 1 && *n >= start && *n <= end;
}
Now, you can call this and check it and use that to loop until you get "valid" input in another function if you want, or simply exit with an error message if that's the desired behavior.
The problem of how to verify that the user actually entered an integer has already been answered in this question:
Validate the type of input in a do-while loop C
Therefore, the question remains how to verify that the integer that the user entered is also in the range 1 to 10.
In order to do this, all you need is an if statement. However, if you want the user to be automatically re-prompted for input, then you will also need a loop.
In my solution below, I use the function get_int_from_user from my solution to the question mentioned above, with a slight modification, so that it accepts printf-style input. This function automatically verifies that the user entered a valid integer, and if not, it automatically reprompts the user for input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <stdarg.h>
#define NUM_JUDGES 3
#define NUM_MOVIES 8
int get_int_from_user( const char *prompt, ... );
int main( void )
{
//Declaration of a 2D array
int movie_scores[NUM_JUDGES][NUM_MOVIES];
//Array of pointers to strings and initializtion
char *movie_names[] = {
"1. <Movie 1>",
"2. <Movie 2>",
"3. <Movie 3>",
"4. <Movie 4>",
"5. <Movie 5>",
"6. <Movie 6>",
"7. <Movie 7>",
"8. <Movie 8>"
};
for( int i = 0; i < NUM_JUDGES; i++ )
{
printf( "Judge %d, rate each movie from 1-10:\n\n", i+1 );
for( int j = 0; j < NUM_MOVIES; j++ )
{
//repeat until the input is in the range 0 to 10
for (;;)
{
int score;
score = get_int_from_user( "%s: ", movie_names[j] );
if ( 0 <= score && score <= 10 )
{
//score is good, so write it to the 2D array and
//break out of the loop
movie_scores[i][j] = score;
break;
}
printf( "Error: The score must be in the range 0 to 10!\n" );
}
}
printf( "\n" );
}
//input is complete, so now it is time to print back the data to the user
printf( "\nThe following data was entered:\n\n" );
for ( int i = 0; i < NUM_JUDGES; i++ )
{
printf( "Judge %d: ", i+1 );
for ( int j = 0; j < NUM_MOVIES; j++ )
{
printf( "%d ", movie_scores[i][j] );
}
printf( "\n" );
}
}
int get_int_from_user( const char *prompt, ... )
{
//loop forever until user enters a valid number
for (;;)
{
char buffer[1024], *p;
long l;
va_list vl;
//prompt user for input
va_start( vl, prompt );
vprintf( prompt, vl );
va_end( vl );
//get one line of input from input stream
if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
{
fprintf( stderr, "Unrecoverable input error!\n" );
exit( EXIT_FAILURE );
}
//make sure that entire line was read in (i.e. that
//the buffer was not too small)
if ( strchr( buffer, '\n' ) == NULL && !feof( stdin ) )
{
int c;
printf( "Line input was too long!\n" );
//discard remainder of line
do
{
c = getchar();
if ( c == EOF )
{
fprintf( stderr, "Unrecoverable error reading from input!\n" );
exit( EXIT_FAILURE );
}
} while ( c != '\n' );
continue;
}
//attempt to convert string to number
errno = 0;
l = strtol( buffer, &p, 10 );
if ( p == buffer )
{
printf( "Error converting string to number!\n" );
continue;
}
//make sure that number is representable as an "int"
if ( errno == ERANGE || l < INT_MIN || l > INT_MAX )
{
printf( "Number out of range error!\n" );
continue;
}
//make sure that remainder of line contains only whitespace,
//so that input such as "6sdfj23jlj" gets rejected
for ( ; *p != '\0'; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( "Unexpected input encountered!\n" );
//cannot use `continue` here, because that would go to
//the next iteration of the innermost loop, but we
//want to go to the next iteration of the outer loop
goto continue_outer_loop;
}
}
return l;
continue_outer_loop:
continue;
}
}
This program has the following behavior:
Judge 1, rate each movie from 1-10:
1. <Movie 1>: abc
Error converting string to number!
1. <Movie 1>: 4abc
Unexpected input encountered!
1. <Movie 1>: 12
Error: The score must be in the range 0 to 10!
1. <Movie 1>: 1
2. <Movie 2>: 2
3. <Movie 3>: 3
4. <Movie 4>: 4
5. <Movie 5>: 5
6. <Movie 6>: 6
7. <Movie 7>: 7
8. <Movie 8>: 8
Judge 2, rate each movie from 1-10:
1. <Movie 1>: 8
2. <Movie 2>: 7
3. <Movie 3>: 6
4. <Movie 4>: 5
5. <Movie 5>: 4
6. <Movie 6>: 3
7. <Movie 7>: 2
8. <Movie 8>: 1
Judge 3, rate each movie from 1-10:
1. <Movie 1>: 10
2. <Movie 2>: 10
3. <Movie 3>: 10
4. <Movie 4>: 10
5. <Movie 5>: 10
6. <Movie 6>: 10
7. <Movie 7>: 10
8. <Movie 8>: 10
The following data was entered:
Judge 1: 1 2 3 4 5 6 7 8
Judge 2: 8 7 6 5 4 3 2 1
Judge 3: 10 10 10 10 10 10 10 10
Note that for demonstration purposes, I have reduced NUM_JUDGES form 5 to 3.
As far as I know, the only option is to simply use scanf. If the number is less than 1 or more than 10, you can print something like "Please enter a number from 1 to 10. and use scanf again until you get a number between 1 and 10.

How to give out a word backwards in c

Can someone help me with my code. I have to create a program, where the user puts in a word and that word has to be given out backwards.
My code doesn't really work, because the backward word puts out some random characters and then gives out the right word.
#include <stdio.h>
int main(){
char word[10];
printf("Please enter a word : ");
scanf("%s", word);
for (int i = 10; i >= 0; i--){
if (word[i] !=0){
printf("%c", word[i]);
}
}
return 0;
}
For starters this call of scanf
scanf("%s", word);
is unsafe. You need at least to specify the length of the entered string like
scanf("%9s", word);
The second problem is that the user can enter less than 9 characters. So this for loop
for (int i = 10; i >= 0; i--){
is incorrect. And moreover the index equal to 10 points to memory outside the array. So this if statement
if (word[i] !=0){
in any case wrong when i is equal to 10.
You need to find the length of the entered string.
The program can look the following way
#include <stdio.h>
#include <string.h>
int main( void )
{
char word[10];
printf( "Please enter a word : " );
if ( scanf( "%9s", word ) == 1 )
{
for ( size_t n = strlen( word ); n != 0; --n )
{
putchar( word[n-1] );
}
putchar( '\n' );
}
}
You're accessing outside the array, since your loop starts at i=10, but the last element of the array is word[9]. And if the user types less than 9 characters, you'll print uninitialized characters.
Use strlen() to determine how long the word is. Then subtract 1 from this to get the index of the last character.
for (int i = strlen(word)-1; i >= 0; i--)
You should also print a newline at the end.

How do you delete the comma after the number?

So I have this exercise from my Coding class and we were tasked to input the user's input. However, we have to remove the comma of the last number of our output, and I'm struggling with how to remove that comma. Can anyone please help?
this is my code
#include <stdio.h>
#define MAX_SIZE 100
int main(){
int arr[MAX_SIZE];
int N, i;
int * ptr = arr;
printf("Enter length: ");
scanf("%d", &N);
for (i = 0; i < N; i++){
printf("Enter element %d: ", i+1);
scanf("%d", ptr);
ptr++;
}
ptr = arr;
printf("[");
for (i = 0; i < N; i++)
{
printf("%d,", *ptr);
ptr++;
}
printf("]");
return 0;
}
for convenience, this is the output I got
Enter length: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
[1,2,3,4,5,]
this is how the output should be
Enter length: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
[1,2,3,4,5]
Simple:
const char *sep = "";
printf( "[" );
for( i = 0; i < N; i++ ) {
printf( "%s%d", sep, arr[ i ] );
sep = ",";
}
printf( "]" );
Put the commas BEFORE the next value to be printed.
Specify the "prefix" to be "", until that is changed to ","
You'd be better off using "array indexing" throughout instead of shifting a pointer around the place... Too easy to forget to reset it to the beginning...
AND, add some code to check that scanf has assigned an integer value to the uninitialised variable 'N'! If the user types "four" in response to the first prompt, the value of N could be anything, even 243,478,658.... That's a LOT of data to be entering... In addition, the code should also check if the user types 120 to fill the 100 elements of the array.
EDIT: In this instance (surrounding brackets), we can even eliminate one line of code.
const char *sep = "[";
for( i = 0; i < N; i++ ) {
printf( "%s%d", sep, arr[ i ] );
sep = ",";
}
printf( "]" );
and then go on to please the "brace-o-phobes" by changing things around
i = 0;
for( char pre = '['; i < N; pre = ',' )
printf( "%c%d", pre, arr[ i++ ] );
putchar( ']' );
You can use a simple ternary to control the format-string in printf, e.g.
for (i = 0; i < N; i++)
{
printf(i ? ",%d" : "%d", *ptr);
ptr++;
}
That only prints a comma before the number for numbers after the first. An equivalent long-form using if-else would be:
for (i = 0; i < N; i++)
{
if (i) {
printf(",%d", *ptr);
}
else {
printf("%d", *ptr);
}
ptr++;
}
Also suggest the final puts ("]"); to ensure your program is POSIX compliant -- outputting a final '\n' before program exit. Likewise, there is no need to call the variadic printf() function to output a single-character. A simple putchar ('['); will do.

Building a pyramid of letters in C99

#include <stdio.h>
#define FINISH 'Z'
int main(void){
int spacenm, currentspacenm, i;
char ini, inirecord;
int rownm, currentrownm;
printf("PLease enter a random uppercase letter: ");
scanf("%c", &inirecord);
spacenm = rownm = FINISH - inirecord;
for (i = 0; i<= spacenm; i++)
printf(" ");
printf("%c\n", inirecord);
i = 0;
for (currentrownm = 1; currentrownm <= rownm; currentrownm ++){
for (currentspacenm = 1; currentspacenm <= spacenm; currentspacenm++)
printf(" ");
spacenm--;
for (ini = inirecord; ini<=inirecord+i; ini++)
printf("%c", ini);
i++;
for (; ini>=inirecord; ini--)
printf("%c", ini);
printf("\n");
}
return 0;
}
I wonder if there're better ways where less variables are needed or less redundant code structure is used to improve efficiency.
We beginners should help each other.:)
There is no check in your program relative to whether the user input is valid.
Also if I'm not mistaken not all coding tables as for example the EBCDIC table contain sequentially upper letters.
There is no need to write a separate snippet of code to output the first row of the pyramid as you are doing
for (i = 0; i<= spacenm; i++)
printf(" ");
printf("%c\n", inirecord);
Using formating you can eliminate the number of loops.
Take into account that in general instead of this format specification
scanf("%c", &inirecord);
^^^^
you should use the following
scanf(" %c", &inirecord);
^^^^^
Otherwise control characters will be also read.
Here are my three cents.:)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
const char *letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const size_t N = strlen( letters );
while ( 1 )
{
char alpha[3];
_Bool exit_status;
const char *p;
do
{
printf( "PLease enter a random uppercase letter (Enter - exit ): " );
exit_status = fgets( alpha, sizeof( alpha ), stdin ) == NULL || alpha[0] == '\n';
if ( !exit_status )
{
p = NULL;
if ( alpha[1] == '\n' )
{
alpha[0] = toupper( ( unsigned char )alpha[0] );
p = strchr( letters, alpha[0] );
}
}
} while ( !exit_status && !p );
if ( exit_status ) break;
int n = &letters[N] - p;
putchar( '\n' );
for ( int i = 0; i < n; i++ )
{
printf( "%*c", n - i, alpha[0] );
int j = 0;
while ( j != i ) putchar( p[++j] );
while ( j != 0 ) putchar( p[--j] );
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
PLease enter a random uppercase letter (Enter - exit ): Z
Z
PLease enter a random uppercase letter (Enter - exit ): Y
Y
YZY
PLease enter a random uppercase letter (Enter - exit ): X
X
XYX
XYZYX
PLease enter a random uppercase letter (Enter - exit ): A
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA
PLease enter a random uppercase letter (Enter - exit ):

C programming, segmentation fault core dump

I am trying to make a program which takes in a input of "Hello" and outputs "olleH" from reversing the order of the characters. However I keep getting a segmentation fault and I don't understand why
#include <stdio.h>
#include<string.h>
int main()
{
int i;
int size;
char s[100],a[100];
printf("Enter the word you want to get reversed: ");
scanf("%s",s);
while(s[i]!='\0')
{
a[i]=s[i];
i++;
}
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
printf("The reversed string is : %s",s);
}
Another simple way to reverse string.
Try this:
while(s[++i]!='\0'); // find the size of string
while(i>=0)
a[j++] = s[--i]; // reverse the string
a[j]='\0';
printf("The reversed string is : %s",a);
This while loop
while(i<sizeof(s))
{
s[i]=a[size];
}
does not make sense because index i has a value that points to outside the entered string (provided that it was initially correctly initialized) and the loop is infinite because i is not changed (and was not initially initialized) in the loop and also the right hand expression of this statement
s[i]=a[size];
is always the same and again refers memory outside the array.
Take into account that neither function declared in <string.h> is used in the program. So the header may be removed.
The program can look the following way
#include <stdio.h>
#define N 100
int main()
{
char s[N], d[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
for ( size_t i = 0; i != n; i++ ) d[i] = s[n-i-1];
d[n] = '\0';
printf( "The reversed string is : %s\n", d );
return 0;
}
You can reverse a string without using an auxiliary array. For example
#include <stdio.h>
#define N 100
int main()
{
char s[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
s[n] = '\0';
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
printf( "The reversed string is : %s\n", s );
return 0;
}
The problem is in this part:
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
sizeof(s) will be 100 whereas the string you read from input can be less than that -- which would be undefined if you access uninitialized parts of s. So, you want to use strlen() to get the actual size of the string and use it to reverse.
Notice that scanf() is unsafe as it's written (what if you input more than 100 chars?). Suggest using fgets() instead.

Resources