Linux Quiz #2: C Programming and Tracing
How do you define a constant?
#define PI 3.14159 OR const float PI = 3.14159
Write a C program that prompts the user to enter two real numbers (numbers with fractions, ex: 3.75) and then computes the sum of the two numbers and prints the result.
#include<stdio.h> int main( ) { float num1, num2, sum; printf( "Enter two real numbers :"); scanf("%f %f", &num1, &num2); sum= num1 + num2; printf( "\n The sum is : %.1f ", sum); }
CHECK and COMPLETE (im getting 0...)
#include<stdio.h> int main(){ double num1, num2, sum; printf( "Enter two real numbers:\n"); scanf("%f %f", &num1, &num2); sum = num1 + num2; printf( "%0.1f", sum); return 0; } #include<stdio.h> int main(){ int num1, num2, product; printf("Enter two integers: \n"); scanf("%d %d", &num1, &num2); product = num1 * num2; printf("%d", product); return 0; }
Write a program to ask the user to enter a string and an integer, then print entire input of the player formatted
#include<stdio.h> main( ) { char str[100]; int i; printf( "Enter a string and an integer :"); scanf("%s %d", str, &i); printf( "\nYou entered: %s %d ", str, i); } Sample Output: ./a.out Enter a string and an integer: Five 5 You entered: Five 5
Write a program that takes a string of length 100 from a user and prints the string until end of line (basic functions)
#include<stdio.h> main( ) { char str[100]; printf( "Enter a string :"); gets( str ); printf( "\nYou entered: "); puts( str ); }
Write a program to ask the user to enter a character/word and print just the first character of that word
#include<stdio.h> main( ) { int c; printf( "Enter a character:"); c = getchar( ); printf( "\n You entered: "); putchar( c ); }
Reading from file example: Write code that opens test.txt and reads from the file characters, and prints to console.
/ * Make sure to create the test.txt file in the same directory */ #include<stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("test.txt", "r"); fscanf(fp, "%s", buff); printf(" %s\n", buff ); fclose(fp); }
Write a C program that prints "Hello World"
/* Sample C program */ #include<stdio.h> int main() { printf("Hello world\n"); return 0; }
Example of writing to file: Write code to append to a file, and to test both functions for writing to a file
/* This will append two lines to the test.txt file */ #include<stdio.h> main() { FILE *fp; fp = fopen("test.txt", "a"); if(fp==NULL) { printf("Error, unable to open the file\n"); } fprintf(fp, "This is testing for fprintf function\n"); fputs("This is testing for fputs function\n", fp); fclose(fp); }
History of C
C programming language is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie and Brian Kernighan to develop the UNIX operating system at Bell Labs.
When to use C language?
The LINUX/UNIX operating systems, the C compiler, and essentially all LINUX/UNIX application programs have been written in C. C programming language has now become a widely used professional language for various reasons: • Easy to learn. • It produces efficient programs. • It can handle low-level activities. • portability.
Opening & closing Files
fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. fclose( ) function. The prototype of this function is: int fclose( FILE *fp ); The fclose() function returns zero on success, or EOF if there is an error in closing the file.
getchar() and putchar() Functions
int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in a loop in case you want to read more than one character from the screen. int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. AKA • char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). • int puts(const char *s) function writes the string 's' and a trailing newline to stdout.
What does the first f in functions like fscanf() mean?
It means that it works with a file stream
What are the components of C?
A C program basically consists of the following components: • Preprocessor Commands • Functions • Variables • Statements & Expressions • Comments
What are C storage classes?
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. These specifiers precede the type that they modify. • auto • register • static • extern
How to write to a file?
• Following is the simplest function to write individual characters to a stream: int fputc( int c, FILE *fp ); The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream: int fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. (REVIEW)
How to read from file:
• Given below is the simplest function to read a single character from a file: int fgetc( FILE * fp ); The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. • The following function allows to read a string from a stream: char *fgets( char *buf, int n, FILE *fp ); The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. (REVIEW)
Auto storage class
• The all-local variables which are defined within a function are known as auto (automatic) variables unless not specified i.e., by default a local variable is an auto variable. • No need to put the keyword auto (it's an optional) while declaring a local variable. • An auto variable is created each time when the function (in which variable is declared) is called and destroyed when the program's execution leaves the function.
Extern storage class
• The extern storage class is used to give a reference of a global variable that is visible to all program files. • The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
Register storage class
• The register storage class is used to define local variables that should be stored in a register instead of RAM. • This means that the variable has a maximum size equal to the size of the register (usually one word) { register int miles; } • The register should only be used for variables that require quick access such as counters. • It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
Static Storage Class
• The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. • Therefore, making local variables static allows them to maintain their values between function calls. • The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
What is the problem with fscanf() function? Write code that reads from test.txt and gets all the characters, then prints them to console.
• fscanf() function reads only up to whitespaces. • To fix this problem use, fgets() function (which reads until new line or end of file) #include<stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("test.txt", "r"); fgets(buff, 254, fp); printf(" %s\n", buff ); fclose(fp); }
scanf() and printf() Functions
• int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided. • int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character, or float, respectively. There are many other formatting options available which can be used based on requirements.
Typedef Vs Define
• typedef is limited to giving symbolic names to types only, whereas #define can be used to define alias for values as well, e.g., you can define 1 as ONE, etc. • typedef interpretation is performed by the compiler whereas #define statements are processed by the preprocessor.
