





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This file contains notes about c programming
Typology: Lecture notes
1 / 29
This page cannot be seen from the preview
Don't miss anything!






















1. Distinguish between a[10] and (a)[10].
(a)[10* ] means that a is now a pointer to a particular data type (e.g. int, char) array of size 10.
*a[10] means that a is an array of 10 particular data type‟s (e.g. int, char) pointers.
2. Discuss chain of pointer with example.
A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example:
#include <stdio.h>
int main () {
int var; int *ptr; int **pptr;
var = 3000;
/* take the address of var / ptr = &var; / take the address of ptr using address of operator & */ pptr = &ptr;
/* take the value using pptr */ printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr);
return 0; }
When the above code is compiled and executed, it produces the following result:
Value of var = 3000
Value available at *ptr = 3000 Value available at **pptr = 3000
3. How can you pass pointers to a function?
A pointer can be passed to a function as an argument. Passing a pointer means passing address of a variable instead of value of the variable. As address is passed in this case, this mechanism is also known as call by address or call by reference. When a pointer is passed to a function while function calling, the formal argument of the function must be compatible with the supplied pointer in the actual argument (For example: If an integer pointer is being passed, the formal argument in function must be pointer of the type integer and so forth). As address of a variable is passed in this mechanism, if value stored in the passed address is changed within function definition the value of actual variable is also changed.
Write a program to illustrate the use of passing pointer to a function.
void addGraceMarks(int *m) { *m = *m+10; } int main() { int marks; printf(‚Enter actual marks: \t‛); scanf(‚%d‛, &marks); addGraceMarks(&marks); //passing address not value */ printf(‚\n The graced marks is: \t %d‛, marks); getch(); return 0; }
4. Define the following terms:
A. Character Set – The set of characters that are used to form words, numbers and expression in C is called c character set. The combination of these characters form words, numbers and expressions in C. The characters in C are grouped in to the following four categories:
Letters and alphabets Digits Special Characters White Spaces
B. Keywords: Keywords are predefined words for a C programming language. All keywords have fixed meaning and these meanings cannot be changed. They serve as basic building blocks for program statements. Some ANSI C keywords are: auto, double, int, struct, break, else, long, switch, case, short, void, while, default, continue, goto, extern, return, char etc.
C. Identifiers: Every word used in C program to identify the name of variables, functions, arrays, pointers and symbolic constants are known as identifiers. They are names given by the user and consist of a sequence of letters and digits, with a letter as the first character. The underscore character can also be used to link between two words in long identifiers.
5. What is a Header File?
Header file in C is a file having .h extension. There are several built-in C functions like printf(), scanf(), getch() defined in C library with as a header file having its .h extension. Inclusion of header files in the program is the pre-information to the compiler regarding the library functions used and its relevant codes to be executed. This type of pre-information is called compiler directives or preprocessor directives.
6. Describe the basic Structures of C Program.
Documentation Section
This section contains a set of comment lines giving the names of program, the author, algorithms, methods used and other details which will be useful in future for users and developing teams.
The documentation acts as a communication medium between members of the development team when a number of developers are working in the same project. It is used by maintenance engineers to update and upgrade the system in future.
It helps while debugging and testing the program. It tells users “how to use and administer the system.” It acts as a user manual.
For example, the title of a program can be written in this section as,
/* This program displays natural numbers from 1 to 10 */
Link Section
This section provides instruction to the compiler to link functions with program from the system library. For example, the statement: #include<stdio.h> links input/output functions like printf() and scanf() with the program. This section is also called the header declaration section. We included a set of header files in which several built-in functions are defined in the libraries under these header files.
Definition Section
In this section, all symbolic constants are defined.
Global Declaration Section
The variables which are used in more than one functions or blocks are called global variables. These variables are defined or declared in this section.
This section also declares all the user-defined functions. User-defined functions or programmer's functions are generally declared in this section to inform the compiler about the name of function, its return types (if any) and the data types of the function arguments (if any) used. This type of function declaration is called function prototyping.
main() Function Section
Every C program starts with a main() function. Within main() function, there are declaration and executable parts. The declaration part declares all the variables used in the execution part. For example, declarations can be done as,
int n1;
int n3 = 5;
The execution part has executable operations like,
n1 = n1 + 1; n2 = n2 * 5;
Subprogram Section
This section contains all the user-defined functions that are called in the main function.
7. Write short note on: Escape Sequences
An escape sequence is a non-printing characters used in C. It is a character combinations consisting of a backslash () followed by a letter or by a combination of digits. It is as a single character and is therefore valid as a character constant. Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminal and printers. They are also used to provide literal representations of non-printing characters and characters that usually have special meanings, such as the double quotation mark (“). The following table lists the ANSI escape sequences and their purposes.
Escape Sequence
Purpose
\a (^) Alert purpose by an audible alert or beep sound. \b (^) Backspace to delete one character to the left of current cursor position \f (^) Form feed to feed a blank page when the user prints the document. \n (^) Line feed or move cursor to the next or new line of the screen. \r (^) Carriage return to move cursor to the next line during typing. \v (^) Vertical tabs to assign more space from the previous line. \t (^) Horizontal tabs to move cursor to the next tab stop position. ' (^) For single quote \” (^) For double quote \ (^) For backslash ** (^0) For null character
8. Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C.
You can easily move your data from one computer to another without any changes.
9. Define Symbolic Constants with appropriate examples.
A symbolic constant is a name that is used in place of a sequence of characters. The character may represent numeric constant, a character or a string constant. When a program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. These constants are defined at the beginning of the program. Preprocessor directive like # define allow an identifier to have a constant value throughout the program. Hence the symbolic constant can simply be defined like:
Syntax of free(): free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Example 1: malloc() and free()
This program calculates the sum of n numbers entered by the user. To perform this task, memory is dynamically allocated using malloc(), and memory is freed using free() function.
#include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0;
printf("Enter number of elements: "); scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); }
printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); }
printf("Sum = %d", sum); free(ptr); return 0; }
Example 2: calloc() and free()
This program calculates the sum of n numbers entered by the user. To perform this task, calloc() and free() is used.
#include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated.");
exit(0); }
printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); }
printf("Sum = %d", sum); free(ptr); return 0; }
C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using realloc() function
Syntax of realloc(): ptr = realloc(ptr, x);
Here, ptr is reallocated with new size x.
Example 3: realloc()
#include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%u\n",ptr + i);
printf("\nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: "); for(i = 0; i < n2; ++i) printf("%u\n", ptr + i); return 0; }
When you run the program, the output will be:
Enter size of array: 2 Addresses of previously allocated memory: 26855472
sizeof (type)
Logical negation Bitwise(1 's) complement Unary plus Unary minus Increment Decrement Dereference Operator(Address) Pointer reference Returns the size of an object Type cast(conversion)
Right to left
Multiply Divide Remainder
Left to right
Binary plus(Addition) Binary minus(subtraction)
Left to right
Left shift Right shift
Left to right
Less than Less than or equal Greater than Greater than or equal
Left to right
Equal to Not equal to
Left to right
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Right to left
*= = /= %=
- = &= ^= |= <<=
Simple assignment Assign product Assign quotient Assign remainder Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR
Right to left
>>= Assign left shift Assign right shift
, Separator of expressions Left to right
14. Write short note on: goto Statement?
The goto statement is used to alter the normal sequence of program execution by unconditionally transferring control to some other part of the program. The goto statement transfers the control to the labeled statement somewhere in the current function. The syntax for goto statement is:
goto label;
Here, label is an identifier used to label the target statement to which the control would be transferred. The target statement must be labeled somewhere in the same program using syntax.
label: statements;
Generally, the use of goto statement is avoided as it makes program illegible. The use of goto statement makes the code very hard to read. This can be an annoyance when trying to understand code written by other people using goto construct. However, the goto statement can be used in following situations:
I. To make branching around statement or group of statements under certain conditions.
II. To Jump to the end of a loop under certain conditions, thus bypassing the remainder of the loop during current pass.
III. To jump completely out of the loop under certain conditions, terminating the execution of a loop.
Write a program to ask two numbers. Display message “Either number is negative” if either number is negative; otherwise display message “Both numbers are positive”.
int i, num1, num2; printf(‚Enter first number:‛); scanf(‚%d‛, &num1);
if(num1 < 0) goto negative; printf(‚Enter second number:‛); scanf(‚%d‛, &num2);
if(num2<0) goto negative; printf(‚Both numbers are positive‛); getch(); return;
negative: printf(‚Either number is negative‛); getch(); return 0;
15. Explain switch statement briefly.
19. Contrast with suitable examples, the difference between iteration and recursion.
Recursion and iteration both repeatedly executes the set of instructions. Recursion is when a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly executes until the controlling condition becomes false. The primary difference between recursion and iteration is that is a recursion is a process, always applied to a function. The iteration is applied to the set of instructions which we want to get repeatedly executed.
BASIS FOR COMPARISON
Basic The statement in a body of function calls the function itself.
Allows the set of instructions to be repeatedly executed. Format In recursive function, only termination condition (base case) is specified.
Iteration includes initialization, condition, and execution of statement within loop and update (increments and decrements) the control variable. Termination A conditional statement is included in the body of the function to force the function to return without recursion call being executed.
The iteration statement is repeatedly executed until a certain condition is reached.
Condition If the function does not converge to some condition called (base case), it leads to infinite recursion.
If the control condition in the iteration statement never becomes false, it leads to infinite iteration. Infinite Repetition
Infinite recursion can crash the system. Infinite loop uses CPU cycles repeatedly.
Applied Recursion is always applied to functions.
Iteration is applied to iteration statements or "loops". Stack The stack is used to store the set of new local variables and parameters each time the function is called.
Does not use stack.
Overhead Recursion possesses the overhead of repeated function calls.
No overhead of repeated function call.
Speed Slow in execution. Fast in execution. Size of Code Recursion reduces the size of the code. Iteration makes the code longer. Example #include <stdio.h> int factorial(int n){ if(n == 0) return 1; else return n * factorial(n- 1); }
int main() { printf("Factorial for 5 is
#include <stdio.h> int main() { int i, n = 5, fac = 1;
for(i = 1; i <= n; ++i) fac = fac * i;
printf("Factorial for 5 is %d", fac);
return 0;
%d", factorial(5));
return 0; }
20. How nested structure is defined and initialized? Explain with an example.
Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure as we declare structure members inside a structure.
The structure variables can be a normal structure variable or a pointer variable to access the data. You can learn below concepts in this section.
1. STRUCTURE WITHIN STRUCTURE IN C USING NORMAL VARIABLE:
This program explains how to use structure within structure in C using normal variable. ‚student_college_detail‛ structure is declared inside ‚student_detail‛ structure in this program. Both structure variables are normal structure variables.
Please note that members of ‚student_college_detail‛ structure are accessed by 2 dot(.) operator and members of “student_detail‛ structure are accessed by single dot(.) operator.
#include <stdio.h> #include <string.h>
struct student_college_detail { int college_id; char college_name[50]; };
struct student_detail { int id; char name[20]; float percentage; // structure within structure struct student_college_detail clg_data; }stu_data;
int main() { struct student_detail stu_data = {1, "Raju", 90.5, 71145, "Anna University"}; printf(" Id is: %d \n", stu_data.id); printf(" Name is: %s \n", stu_data.name); printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id); printf(" College Name is: %s \n", stu_data.clg_data.college_name); return 0;
}
Name is: Raju Percentage is: 90. College Id is: 71145 College Name is: Anna University
21. What are the advantages of using function?
(a) Manageability: The use of function to perform specific job in a program makes easier to write small programs (i.e. small program blocks) and keep track of what they do. It makes programs significantly easier to understand and maintain by breaking them up into easily manageable chunks. The code for each job or activity is placed in individual function such that testing and debugging becomes easy and efficient. Thus, the use of functions in a program helps to manage the code.
(b) Code Reusability: A single function can be used (i.e. called) multiple times in a single program from different places (i.e. the same code of function is used again and again reused). It avoids rewriting the same code again and again such that it reduces extra effort. Thus, it helps to reuse the code once written and tested. The C standard library is an example of functions reused.
(c) Non-redundant (non-repeated) programming (i.e. avoids redundant programming): A function written once is called multiple times in the program when needed to perform the specified task. The particular job or activity that is to be accessed repeatedly multiple times from several different places within or outside the program is written within function. If the function is not used in such situations, the code for same activity is to be re-written every time. Thus, the use of function avoids the need of redundant programming for the task.
(d) Logical Clarity: When a single program is decomposed into various well-defined functions, the main program consists of a series of function calls rather than countless line of code so that the size of main program seems small and program becomes logically clear to understand. It helps to make program easier to write, understand, debug and test.
(e) Easy to divide the work among programmers: The number of programmers working on one large project can divide the workload on the basis of functions (i.e. one may write one function and other may write another function.) Finally, they can be integrated in the program.
22. Write about unformatted functions with examples.
Unformatted functions do not allow the user to read or display data in desired format. These types of library functions basically deal with a single character or a string of characters. The functions getchar(), putchar(), gets(), puts(), getch(), getche(), putch() are considered as unformatted functions.
I. getchar() and putchar() – The getchar() function reads a character from a standard input device.
Syntax: character_variable = getchar(); The getchar() function makes wait until a key is pressed and then assigns this character to character_variable.
The putchar() function displays a character to the standard output device.
Syntax: putchar (character_variable);
Write a program to read a character from keyboard using getchar() function and display on the screen using putchar() function.
#include<stdio.h> #include<conio.h> int main() { char gender; printf(‚Enter gender M or F:‛ ); gender = getchar(); printf(‚Your gender is: ‛); putchar(gender); getch(); return 0; }
II. getch(), getche() and putch() - The function getch() and getche() reads a single character in the instant it is typed without waiting for the enter key to be hit. The difference between them is that getch() reads the character typed without echoing it on the screen, while getche() reads the character and echoes (displays) it onto the screen.
Syntax: character_variable = getch(); character_ variable = getche();
In both functions, the character typed is assigned to the char type variable character_variable.
The functions putch() prints a character onto the screen.
Syntax: putch(character_variable);
Write a program to read two characters from keyboard: one using getch() and another using getche() function and displays the characters using putch() function
#include<stdio.h> #include<conio.h> int main() { char ch1, ch2; printf(‚Enter 1st character: ‛); ch1 = getch(); printf(‚\n Enter 2nd character: ‛); ch2 = getche(); printf(‚\n 1st character: ‛); putch(ch1); printf(‚\n 2nd character: ‛); putch(ch2); getch(); return 0; }
23. What is Address Operator?
The operator & is also known as address operator as we can represent address of a variable using this operator. Thus, &a denotes the address of variable a.
24. How do you initialize pointer?
Step By Step Execution of C Program
Step 1: Edit
Step 2: Compiling
Step 3: Checking Errors
Step 4: Linking Libraries
Step 5: Error Checking
A recursive function is one that calls to itself to solve a smaller version of its task until a final call which does not require a self-call. Thus, a function is known as recursive function if it calls to itself. The recursion in programming is a technique for defining a problem is built on the results from the smaller versions. The recursion is used for repetitive computations in which each action is stated in term of previous result. Many iterative or repetitive
problems can be written in recursive form. But it is not necessary that all problems can be solved using recursion. To solve a problem using recursive method, the following two conditions must be satisfied.
I. Problem could be written or defined in term of its previous result.
II. Problem statement must include a stopping condition (i. e. we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return.)
28. Differentiate between continue statement and break statement.
BASIS FOR COMPARISON
Task It terminates the execution of remaining iteration of the loop.
It terminates only the current iteration of the loop. Control after break/continue
'break' resumes the control of the program to the end of loop enclosing that 'break'.
'continue' resumes the control of the program to the next iteration of that loop enclosing 'continue'. Causes It causes early termination of loop. It causes early execution of the next iteration. Continuation 'break' stops the continuation of loop. 'continue' do not stops the continuation of loop, it only stops the current iteration. Other uses 'break' can be used with 'switch', 'label'. 'continue' cannot be executed with 'switch' and 'labels'. Example #include<stdio.h> int main() { int i; for(i = 0; i < 10; i++) { if( i % 4 == 0 ) { /*when i is divisible by 4, go out of the iteration */ break; } printf("%d\n", i); } return 0; }
#include<stdio.h> int main() { int i; for(i = 0; i < 10; i++) { if( i % 4 == 0 ) { /*when i is divisible by 4, continue to the next iteration */ continue; } printf("%d\n", i); } return 0; }
29. What are the different types of Operators on the basis of the number of operands they require?
(a) Unary Operators: The operators which require only one operand are known as unary operators. Examples: ++ (increment operator), -- (decrement operator), - unary minus), and + (unary plus) are unary operators. Examples of expressions involving unary operators: x++, y=-k.
(b) Binary Operators: The operators which require two operands are known as binary operators. For example: + (plus), - minus), * (multiply), / (division), < (less than), > (greater than), etc.
(c) Ternary Operators: The operators that require three operands are known as ternary operators. Example: ‚? : ‛ (conditional operator)