I have a question
"Write a C program that accepts as input a single integer k, then writes a pattern consisting of a single 1 on the first line, two 2s on the second line, three 3s on the third line, and so forth, until it writes k occurrences of k on the last line."
For example, if the input is 5, the output should be the following:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
I have written the below code to achieve this.
#include <stdio.h>
#include <stdlib.h>
int main() {
int k = 5;
int i;
int j;
for(i = 1; i<=k; i++){
for(j = 1; j<=i; j++){
printf('%d',i);
}
printf('\n');
}
return 0;
}
When I run this program, Eclipse crashes. Is there something I am missing in the code I wrote ?
printf('%d',i);
should be
printf("%d",i);
The first argument of printf() expects const char * and what you have is a character for it. Compiler should have thrown a warning for this before you went ahead and hit a crash. Don't ignore warnings!!
You need to change
printf('%d',i);
to
printf("%d",i);
and also,
printf('\n');
to
printf("\n");
Reason: As per the man page of printf(), the function prototype is
int printf(const char *format, ...);
which says, the first argument should be a const char *.
Usually, " " is used to denote (const) char * as oppossed to ' ' which is used to denote a char constant.
Note: Enable warnings in your compiler and pay heed to them. Most of the time compiler warns you about the mistatch in agument and parameter type mismatch.
In printf, you have to pass the character pointer.
change this
printf('%d',i);
into
printf("%d",i);
printf definition.
int printf(const char *format, ...);
If you look into documentation of C programming printf function require a string i.e. const char *format, and string is represented by double quotes(" "). So replace single quotes (' ') by double quotes (" ").
The output format for printf in c library is
printf("data type representation", the data to be printed);
So in output stream you must use double quotes instead of single.
Following code will work fine,
#include <stdio.h>
int main(void) {
// your code goes here
int k,i,j;
scanf("%d",&k);
for(i=1;i<=k;i++)
{
for(j=1;j<=i;j++)
printf("%d",i);
printf("\n");
}
return 0;
}
Related
I recently encountered with an interview question. I did not understand the behaviour of printf function in this case
#include <stdio.h>
int main() {
int k = printf("String");
printf("%d",k);
}
Expected result : Compilation Error
Output : String6
Why is the output String6?
Here is the prototype for printf:
int printf(const char *format, ...);
We can see that printf returns an int.
The documentation indicates that:
Upon successful return, these functions return the number of
characters printed (excluding the null byte used to end output to
strings).
You asked why the output is "String6". Well:
printf("String");
This first prints String but does not print a newline character. Since String is 6 characters, printf returns 6, which you store in k:
printf("%d",k);
This then prints 6 (on the same line).
Try running this program:
#include <stdio.h>
int main(void)
{
int bytes_printed = printf("%s\n", "String");
// 7 = 1 + 6
printf("printf returned: %d\n", bytes_printed);
return 0;
}
Output:
String
printf returned: 7
the printf() function returns the number of character it printed. Since you set int k = printf("String");, the print function is executing printing out "String" and setting k equal to 6 since "String" is 6 characters long, then your second call to printf prints the value of k which is 6, resulting in the console displaying "String6".
This is perfectly valid C syntax.
I am trying to compare two set of data using strcmp. This first set of data are var1 which is get from fgets(var1, 100, stdin). The second set of data are generate randomly by rand. When I complie it, I get two same errors. They both come from char f.
warning: assignment makes pointer from integer without a cast printf(f);
warning:assignment makes pointer from integer without a cast if (strcmp(var1,f)==0)
i already declare the randomly generated number char f = rand() % 38; in char, why will it not work?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
fgets(var1, 100, stdin);
srand(time(NULL));
char myArray[38] = { 1,5,3,4};
char f = rand() % 38;
printf(var1);
printf(f);
if (strcmp(var1,f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
EDITED CODE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
scanf("%s",var1);
srand(time(NULL));
char myArray[7] = { 0,28,9,26,30,11,7 };
int randomindex= 1 + (rand() % 100);
char f = myArray[randomindex];
char str_f[2] = { f, '\0' };
printf("var1: %s\n",var1);
printf("%s",str_f);
printf("\n");
if (strcmp(var1,str_f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
As commented above, in C Langage, functions from Library have a strict format and using not that expected format will occur warning or error at compilation time or runtime.
Function 1 - the printf() is the common function to write C strings to the standard output stdout (declared in <stdio.h>).
See the C library function - printf()
int printf(const char *format, ...)
In the provided source code, the printf() function has been used in the following cases:
printf("It work\n"); to write a fixed string which complies with the const char * expected format of the first parameter ==> OK,
printf(var1); to write the content of the entered string var1 (declared as char var1[100];) which not exactly complies with const char * of the first parameter but will be cast during compile time. A proposed format to write the var1 string could be printf("%s",var1); (or more verbose printf("var1: %s",var1);) where the first parameter "%s" will specify that the following argument var1 will be a string.
printf(f); to write the content of the random value (declared as char f;) which doesn't comply with const char * of the first parameter and doesn't compile at all. The minimal expected format to write the f character is printf("%c",f); (or more verbose printf("f=%c",f);) where the first parameter "%c" will specify that the following argument f will be a character.
Function 2 - the strcmp() is a function to compare two C strings parameters (declared in <string.h>.
See the C library function - strcmp()
int strcmp(const char *str1, const char *str2)
In the provided source code, the strcmp() function has not been used as specified. The function expects two input parameters:
First parameter of strcmp(var1,...)==0 is var1 (declared as char var1[100];) which not exactly complies with const char * but will be cast during compile time.
Second parameter of strcmp(...,f)==0 is f (declared as char f;) which doesn't comply with const char * and doesn't compile at all.
To compare the character f with var1, it shall be necessary to
convert it to a string (In C, a string is an array of char ended by
a character).
Solution 1 - how to convert the character char f; to a string.
A C string is an array of characters: char str_f[]= { '<char>', ... , '<NUL>' };. Meaning that a minimal array of 2 characters is necessary to convert the character char f; to a string.
char f = rand() % 38;
// use a 2 characters string
char str_f[2] = { f, '\0' };
// Could be also initialised as str_f[0] = f; str_f[1] = '\0';
// compare the strings using `str_f`
if (strcmp(var1,str_f)==0) {
Warning 1 - be careful to the random value range.
When printing characters, a C string is supposed to be filled by ASCII
characters different from which is used to end the string.
In the provided source code, the assignment of f, char f = rand() % 38;, will generate values from 0 to 37 which include the character and the first 31 non-printable characters (ctrl-characters). Only characters greater than 31 will be displayed.
In will be more easy to generate: char f = ' ' + (rand() % 38);
where ' ' is the first printable ASCII character = 32.
I'm just toying with the
int main(int argc, int *argv[void])
function, and im trying to make a program that reads the number of number arguments.
Theoretically (in my own crazy delusional mind), this should work:
#include <stdio.h>
int main(int argc, char *argv[])
{
int count;
printf("%d\n", sizeof(int));
}
but no matter what i put as the argument in the command line, i always get 4 (4 bytes in a word?)
How can I tweak this code a little so that when i type
./program 9 8 2 7 4 3 1
i get:
7
much appreciated!
argc represents the number of command line arguments passed in. You can use that as an index into the second argument to main, argv. If you want all the arguments not including the first one (the program name), then you'll need to decrement argc, and increment argv.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/*
* forget about the program name.
*/
argv++;
argc--;
int i;
unsigned int totalNumbers = 0;
printf("Total number of arguments: %d\n", argc);
for(i = 0; i < argc; i++) {
printf("argv[%d]=%s\n", i, argv[i]);
errno = 0;
long num = strtol(argv[i], NULL, 10);
if(!(num == 0L && errno == EINVAL))
totalNumbers++;
}
printf("Total number of numeric arguments: %u\n",
totalNumbers);
return 0;
}
As others have pointed out in the comments, sizeof doesn't do quite what you think it does.
You are given argc and argv. The second of these is an array of string corresponding to the things on the command line. This argv array of strings is argc long, and the first element of it is likely to hold the name of the executable program.
You need to loop through the remaining elements of argv (if there are any) and see which ones are numbers, as opposed to non-numbers.
To check if a string is a number or not, we can use strtol() (from stdlib.h) to try to convert it into a long. If the conversion fails, it's not a number. If you'd like to accept floating point values, then use strtod() instead, it works almost in the same way (doesn't take the last argument that strtol() does). EDIT: I actually changed the code to use strtod() instead since it accepts a larger variety of "numbers".
The conversion fails if the string is empty from the start, or if the pointer that we supply to the function (endptr) doesn't point to the very end of the string after calling it.
Then, if the argument is a number, simply count it, and at the end tell the user what he or she probably already knew.
What you're doing here is called validating user input and it's a really good thing to know how to do. Don't trust users to give you numbers just because you ask them to. Check to see if they really are numbers by reading in strings and trying to convert them.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool is_number(const char *string)
{
char *endptr;
strtod(string, &endptr);
return (*string != '\0' && *endptr == '\0');
}
int main(int argc, char **argv)
{
int i;
int numcount = 0;
for (i = 1; i < argc; ++i) {
if (is_number(argv[i]))
numcount++;
}
printf("There were %d numbers on the command line\n", numcount);
return EXIT_SUCCESS;
}
Running it:
$ /a.out 1 2 3 a b c -.5 +20 1e20
There were 6 numbers on the command line
$ ./a.out nt 12 ,e2 2 21n 1 -8
There were 4 numbers on the command line
I have the following code which I am trying to run.
I want the scanf function to take in three different inputs, with the first two being integers between 0 and 30, and the third a string beginning with #.
The program compiles fine, but when I attempt to input the coordinates and the associated #symbol, I get a 0 in the y coordinate's place.
Does anyone know why this is happening or what I can do to fix it?
Below is the code
#include <stdio.h>
int main(){
int grid[30][30];
int i, j;
for(i=0; i<30;i++){
for(j=0; j<30;j++){
grid[i][j]='.';
}
}
int x_coord;
int y_coord;
char type[2];
scanf("%d %d %s",&x_coord,&y_coord,type);
/*added extra whitespace*/
printf("%i %i %s",x_coord,y_coord,type);
printf("\n");
grid[x_coord][y_coord]=type[1];
//end outer loop
for(i=0; i<30;i++){
for(j=0; j<30;j++){
printf("%c",grid[i][j]);
}
printf("\n");
}
return(0);
}//end main
As you declared char type[2]; and you are first entering # and then new character suppose X so in type it will go like this
type[0] = #
type [1]='\0'
so you should declare char type[3]; this way
so that
type[0] = #
type [1]='X'
type [2]='\0'
it will stored this way and you can get X by accessing type [1]
Assuming you are entrering #X for the string, where X is some single character, scanf is going to attempt to fill type with '#' 'X' and '\0' (null byte added by scanf to mark the end of the string)
That's 3 bytes being stored in array that is only big enough for two.
My instructor said the way to start this is to use the getline() function from out book, then get the numbers from the line, then have those numbers in matrix form, I do not understand why I would use getline?
//eventually this code should take in a square matrix and from 2x2 to 6x6
//the plan is to get it to read in a line, then get the numbers from the line,
//then print out the numbers in a matrix form. That is the goal for today.
//later I will try to get the actual matrix part working
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//error list for error checking will need later I guess (from my notes)
#define ENDOFFILE -1
#define TOOMANYNUMS -2
#define LIMIT 256
//functions declared
int get_line(char line[], int);
//main
main(){
char line[255];
int num[6];
printf("Please input numbers %c: ", line);
get_line(line,LIMIT);
}
//functions
int get_line(char s[],int lim){
int c, i;
for (i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if(c=='\n'){
s[i]=c;
++i;
}
s[i]='\0';
return i;
}
The getline(char[], int) function reads characters from the console with getchar() and stores them in the array s[]. The array s[] points at the same memory as the line[] array in the main() function.
getline is not just returning the lenth of the line, it's also copying the first line into the s parameter. So after your call of getline(line,LIMIT) (which doesn't btw, store the return value anywhere), the line variable will contain the first line.
Edit: I should also point out that your printf just above the call to getline is referencing the line variable, which is uninitialized and a char array, not a single character