Translate it in your own Language
Showing posts with label C Language. Show all posts
Showing posts with label C Language. Show all posts
Monday, November 28, 2016
Wednesday, August 3, 2016
Dear readers, these C Programming Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C Programming. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
Wednesday, June 4, 2014
What is a file?
• A named collection of data, stored in secondary storage (typically).• Typical operations on files:
– Open
– Read
– Write
– Close
• How is a file stored?
– Stored as sequence of bytes, logically contiguous (may not be physically contiguous on disk).
– The last byte of a file contains the end-of-file character (EOF), with ASCII code 1A (hex).
– While reading a text file, the EOF character can be checked to know the end.
• Two kinds of files:
– Text :: contains ASCII codes only
– Binary :: can contain non-ASCII characters
• Image, audio, video, executable, etc.
• To check the end of file here, the file size value (also stored on disk) needs to be checked.
File handling in C
• In C we use FILE * to represent a pointer to a file.• fopen is used to open a file. It returns the special value NULL to indicate that it is unable to open the file.
FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode in which we open the file. There are three modes."r" opens a file for reading.
"w" creates a file for writing, and writes over all previous contents (deletes the file so be careful!).
"a" opens a file for appending – writing on the end of the file.
• We can add a “b” character to indicate that the file is a binary file.
– “rb”, “wb” or “ab”
fptr = fopen (“xyz.jpg”, “rb”);
The exit() function
• Sometimes error checking means we want an "emergency exit" from a program.• In main() we can use return to stop.
• In functions we can use exit() to do this.
• Exit is part of the stdlib.h library.
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
FILE *fptr;char filename[]= "file2.dat";fptr = fopen (filename,"w");if (fptr == NULL) {printf (“ERROR IN FILE CREATION”);/* Do something */exit(-1);}
Writing to a file using fprintf( )
• fprintf() works just like printf() and sprintf() except that its first argument is a file pointer.FILE *fptr;Fptr = fopen ("file.dat","w");/* Check it's open */fprintf (fptr, "Hello World!\n");fprintf (fptr, “%d %d”, a, b);
Reading Data Using fscanf( )
FILE *fptr;
Fptr = fopen (“input.dat”, “r”);
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
fscanf (fptr, “%d %d”,&x, &y);
Reading lines from a file using fgets( )
We can read a string using fgets().FILE *fptr;char line [1000];/* Open file and check it is open */while (fgets(line,1000,fptr) != NULL){printf ("Read line %s\n",line);}fgets() takes 3 arguments – a string, maximum number of characters to read, and a file pointer. It returns NULL if there is an error (such as EOF).
Closing a file
• We can close a file simply using fclose() and the file pointer.FILE *fptr;char filename[]= "myfile.dat";fptr = fopen (filename,"w");if (fptr == NULL) {printf ("Cannot open file to write!\n");exit(-1);}fprintf (fptr,"Hello World of filing!\n");fclose (fptr);
Three special streams
• Three special file streams are defined in the <stdio.h> header– stdin reads input from the keyboard
– stdout send output to the screen
– stderr prints errors to an error device (usually also the screen)
• What might this do?
fprintf (stdout,"Hello World!\n");
An example program
#include <stdio.h>main()
{
int i;
fprintf(stdout,"Give value of i \n");
fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d \n",i);
fprintf(stderr,"No error: But an example to show error message.\n");
}
Output of program:
Give value of i
15
Value of i=15
No error: But an example to show error message.
Input File & Output File redirection
• One may redirect the standard input and standard output to other files (other than stdin and stdout).
• Usage: Suppose the executable file is a.out:
$ ./a.out <in.dat >out.dat
scanf() will read data inputs from the file “in.dat”, and printf() will output results on the file “out.dat”.
A Variation
$ ./a.out <in.dat >>out.dat
scanf() will read data inputs from the file “in.dat”, and printf() will append results at the end of the file “out.dat”.
Reading and Writing a character
• A character reading/writing is equivalent to reading/writing a byte.
• Example:
char c;
c = getchar();
putchar(c);
Example: use of getchar() & putchar()
#include <stdio.h>
main()
{
int c;
printf("Type text and press return to
see it again \n");
printf("For exiting press <CTRL D> \n");
while((c = getchar()) != EOF)
putchar(c);
}
Friday, May 2, 2014
C keeps a small set of keywords for its own use. These keywords cannot be used as identifiers in the program — a common restriction with modern languages. Where users of Old C may be surprised is in the introduction of some new keywords; if those names were used as identifiers in previous programs, then the programs will have to be changed. It will be easy to spot, because it will provoke your compiler into telling you about invalid names for things. Here is the list of keywords used in Standard C; you will notice that none of them use upper-case letters.
auto | double | int | struct |
break | else | long | switch |
case | enum | register | typedef |
char | extern | return | union |
const | float | short | unsigned |
continue | for | signed | void |
default | goto | sizeof | volatile |
do | if | static | while |
The new keywords that are likely to surprise old programmers are:
const
, signed
, void
and volatile
(although void
has been around for a while). Eagle eyed readers may have noticed that some implementations of C used to use the keywords entry
, asm
, and fortran
. These are not part of the Standard, and few will mourn them.- C Pointer is used to allocate memory dynamically i.e. at run time.
- C Pointer is a variable that stores the address of another variable.
- The variable might be any of the data type such as int, float, char, double, short etc.
Syntax : data_type *var_name;Example : int *p; char *p;
- Where, * is used to denote that “p” is pointer variable and not a normal variable.
Key points to remember about pointers in C:
- Normal variable stores the value whereas pointer variable stores the address of the variable.
- The content of the C pointer always be a whole number i.e. address.
- Always C pointer is initialized to null, i.e. int *p = null.
- The value of null pointer is 0.
- & symbol is used to get the address of the variable.
- * symbol is used to get the value of the variable that a pointer is pointing to.
- If pointer is assigned to NULL, it means it is pointing to nothing.
- Two pointers can be subtracted to know how many elements are available between these two pointers.
- But, Pointer addition, multiplication, division are not allowed.
- The size of any pointer is 2 byte (for 16 bit compiler).
Example program for pointer in C:
#include <stdio.h>
#include<conio.h>
void main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
getch();
}
Output:
50
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure, etc.
Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list ) { body of the function }
A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function:
- Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
- Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
- Function Body: The function body contains a collection of statements that define what the function does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:
/* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:
#include <stdio.h> #include<conio.h> /* function declaration */ int max(int num1, int num2); void main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); getch(); } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type | Description |
---|---|
Call by value | This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
Call by reference | This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. |
By default, C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
Pointer
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Misc Operators
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A - B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by de-numerator | B / A will give 2 |
% | Modulus Operator and remainder of after an integer division | B % A will give 0 |
++ | Increments operator increases integer value by one | A++ will give 11 |
-- | Decrements operator decreases integer value by one | A-- will give 9 |
Relational Operators
Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non-zero, then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
p | q | p & q | p | q | p ^ q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) will give 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) will give 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) will give 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) will give -61, which is 1100 0011 in 2's complement form. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 will give 240 which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 will give 15 which is 0000 1111 |
Assignment Operators
There are following assignment operators supported by C language:
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B will assign value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
Misc Operators ↦ sizeof & ternary
There are few other important operators including sizeof and ? : supported by C Language.
Operator | Description | Example |
---|---|---|
sizeof() | Returns the size of an variable. | sizeof(a), where a is integer, will return 4. |
& | Returns the address of an variable. | &a; will give actual address of the variable. |
* | Pointer to a variable. | *a; will pointer to a variable. |
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Subscribe to:
Posts (
Atom)