Programming in C, 2nd Edition [2020] Nilkani Mort
Programming in C, 2nd Edition [2020] Nilkani Mort
INTRODUCTION TO C
1. #include<stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Features of C Language
C is the widely used language. It provides many features that are given
below.-
• Simple Extensibl
Portable e
• Machine Independent or Portable
Simple
• Mid-level programming language Recursio
• structured programming language n
Rich Library
C provides a lot of inbuilt functions that make the development fast.
Memory Management
It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.
Speed
The compilation and execution time of C language is fast since there are
lesser inbuilt functions and hence the lesser overhead.
Pointer
C provides the feature of pointers. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures,
functions, array, etc.
Recursion
In C, we can call the function within the function. It provides code reusability
for every function. Recursion enables us to use the approach of
backtracking.
Extensible
C language is extensible because it can easily adopt new features.
4|C PROGRAMMING LANGUAGE
First C Program
Before starting the abcd of C language, you need to learn how to write,
compile and run the first c program.
To write the first c program, open the C console and write the following
code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
int main() The main() function is the entry point of every program in c
language.
return 0 The return 0 statement, returns execution status to the OS. The 0
value is used for successful execution and 1 for unsuccessful execution.
.exe Linker
Object file (.o)
C - Basic Syntax
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the
following C statement consists of five tokens −
printf(“Hello world”);
“Hello world”
);
Semicolons
In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the end
of one logical entity.
Given below are two different statements −
printf(“Hello world”);
return 0;
Keywords
A keyword is a reserved word. You cannot use it as a variable name,
constant name, etc. There are only 32 reserved words (keywords) in the C
language.
6|C PROGRAMMING LANGUAGE
Data Types in C
A data type is a classification of data which tells the compiler or interpreter
how the programer intends to use the data. In another word you can say
that it defines the size (BYTE) and the range of a variable.
Already define by the C standard, these are int, char, float, double, …etc.
Using the sizeof operator you can get the size of (in bytes) data types. These
data types are dependent on the platform so C standard also introduces the
fixed size of data type like uint8_t, uint16_t uint32_t …etc. These are
defined in stdint.h header file for more detail you check this header file.
7|C PROGRAMMING LANGUAGE
In C language, different data types have the different ranges. The range
varies from compiler to compiler. In below table, I have listed some data
types with there ranges and format specifier as per the 32-bit GCC compiler.
C Operators
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated
first and next. The associability specifies the operator direction to be
evaluated; it may be left to right or right to left.
Int value=10+20*10;
Comments in C
Comments in C language are used to provide information about lines of
code. It is widely used for documenting code. There are 2 types of
comments in the C language.
2. Multi-Line Comments
1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
5. return 0;
6. }
Output:
Hello C
Even you can place the comment after the statement. For example:
10 | C P R O G R A M M I N G L A N G U A G E
1. /*
2. code
3. to be commented
4. */
1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi-Line Comment*/
5. printf("Hello C");
6. return 0;
7. }
Output:
Hello C
11 | C P R O G R A M M I N G L A N G U A G E
C Format Specifier
The Format specifier is a string used in the formatted input and output
functions. The format string determines the format of the input and output.
The format string always starts with a '%' character.
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character
12 | C P R O G R A M M I N G L A N G U A G E
Output: A
Output: A
In both codes, you can see %c convert data in character and printf function
print it on the console.
13 | C P R O G R A M M I N G L A N G U A G E
Output:
65
65
65
When you are printing using the printf function, there is no specific
difference between the %i and %d format specifiers. But both format
specifiers behave differently with scanf function.
The %d format specifier takes the integer number as decimal but %i format
specifier takes the integer number as decimal, hexadecimal or octal type. it
means the %i automatically identified the base of the input integer number.
14 | C P R O G R A M M I N G L A N G U A G E
Note: You must put ‘0x’ for hexadecimal number and ‘0’ for octal number
while entering the input number.
Output:
15 | C P R O G R A M M I N G L A N G U A G E
Output:
6.270000
6.270000e+000
Output:
16 | C P R O G R A M M I N G L A N G U A G E
6.276240
6.28
6.2762
You can see, how we can control the precision of float by placing elements
with a format specifier. Here %.2f and %.4f will restrict the values up to
two and four decimal values.
Output:
101
Output: b
17 | C P R O G R A M M I N G L A N G U A G E
Output:
aticleworld
Output:
18 | C P R O G R A M M I N G L A N G U A G E
In below code, you can see how – and + is used for left and right alignment.
The value after the decimal represents precision.
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't
represent itself when used inside string literal or character.
\a Alarm or Beep
\b Backspace
\f Form feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\’ Single Quote
\” Double Quote
19 | C P R O G R A M M I N G L A N G U A G E
\? Question Mark
\0 null
Output:
You
are
learning
'c' language
"Do you know C language"
C if else Statement
The if-else statement in C is used to perform the operations based on some
specific condition. The operations specified in if block are executed if and
only if the given condition is true.
o If statement
o If-else statement
o If else-if ladder
20 | C P R O G R A M M I N G L A N G U A G E
o Nested if
If Statement
The if statement is used to check some given condition and perform some
operations depending upon the correctness of that condition. It is mostly
used in the scenario where we need to perform the different operations for
the different conditions. The syntax of the if
statement is given below.
1. if(expression){
2. //code to be executed
3. } False
Condition
1. #include<stdio.h> True
2. int main(){
If Code
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){ After if
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
21 | C P R O G R A M M I N G L A N G U A G E
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }
Output
Enter three numbers?
12 23 34
22 | C P R O G R A M M I N G L A N G U A G E
34 is largest
If-else Statement
The if-else statement is used to perform two operations for a single
condition. The if-else statement is an extension to the if statement using
which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of the
condition. Here, we must notice that if and else block cannot be executed
simultaneously. Using if-else statement is always preferable since it always
invokes an otherwise case with every if condition. The syntax of the if-else
statement is given below.
1. if(expression){
2. //code to be executed if condition is true
Condition False
3. }else{
4. //code to be executed if condition is false
5. }
True
After if
1. #include<stdio.h>
2. int main(){
3. int number=0;
23 | C P R O G R A M M I N G L A N G U A G E
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output:
enter a number:4
4 is even number
enter a number:5
5 is odd number
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18)
8. {
9. printf("You are eligible to vote...");
24 | C P R O G R A M M I N G L A N G U A G E
10. }
11. else
12. {
13. printf("Sorry ... you can't vote");
14. }
15. }
Output:
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
25 | C P R O G R A M M I N G L A N G U A G E
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Condition -1
Condition- 2
Condition-n
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
26 | C P R O G R A M M I N G L A N G U A G E
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output:
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
27 | C P R O G R A M M I N G L A N G U A G E
Output:
Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...
C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which
allows us to execute multiple operations for the different possibles values of
28 | C P R O G R A M M I N G L A N G U A G E
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
expression
Switch Statement
matched
Case-1
Statement-1 break
unmatched
matched
Statement-2 break
Case-2
unmatched
matched
Statement-n break
Case-3
unmatched
default
Statement n+1 break
29 | C P R O G R A M M I N G L A N G U A G E
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
30 | C P R O G R A M M I N G L A N G U A G E
20. }
Output:
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Output:
hi
31 | C P R O G R A M M I N G L A N G U A G E
C Loops
The looping can be defined as repeating the same process multiple times
until a specific condition satisfies. There are three types of loops used in the
C language. In this part of the tutorial, we are going to learn all the aspects
of C loops.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array
or linked lists).
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can
repeat the execution of several parts of the statements. The do-while loop is
32 | C P R O G R A M M I N G L A N G U A G E
mainly used in the case where we need to execute the loop at least once.
The do-while loop is mostly used in menu-driven programs where the
termination condition depends upon the end user.
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
Output
1. Print Hello
2. Print Sau prakashani
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print Sau prakashani
3. Exit
2
Sau prakashani
do you want to enter more?
n
Example 2:
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
34 | C P R O G R A M M I N G L A N G U A G E
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output:
1
2
3
4
5
6
7
8
9
10
Output:
35 | C P R O G R A M M I N G L A N G U A G E
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows
a part of the code to be executed multiple times depending upon a given
Boolean condition. It can be viewed as a repeating if statement. The while
loop is mostly used in the case where the number of iterations is not known
in advance.
1. while(condition){
2. //code to be executed
3. } False
Condition
True
Statement
36 | C P R O G R A M M I N G L A N G U A G E
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output:
1
2
3
4
5
6
7
8
9
10
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }
Output:
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
for loop in C
The for loop in C language is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures
like the array and linked list.
Example:
1. #include<stdio.h>
2. int main(){
Initialization
3. int i=0;
4. for(i=1;i<=10;i++){
Fals
5. printf("%d \n",i); Condition e
6. }
7. return 0;
Tru
8. } eTr
Statement
ue
Output:
1
2 Inc/dec
3
4
5 For-loop
6
7 ststement
8
9
10
Example:
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
39 | C P R O G R A M M I N G L A N G U A G E
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output:
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Example:
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output:
35 36
40 | C P R O G R A M M I N G L A N G U A G E
Example:
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }
Output:
1234
Example:
1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
8. j+=2;
9. k+=3;
10. }
11. }
41 | C P R O G R A M M I N G L A N G U A G E
Output:
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12
Example:
1. #include<stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }
Output:
infinite loop
C break statement
The break is a keyword in C which is used to bring the program control out
of the loop. The break statement is used inside loops or switch statement.
The break statement breaks the loop one by one, i.e., in the case of nested
loops, it breaks the inner loop first and then proceeds to outer loops. The
break statement in C can be used in the following two scenarios:
2. With loop
42 | C P R O G R A M M I N G L A N G U A G E
Syntax:
1. //loop or switch case
2. break;
Example:
1. #include<stdio.h>
2. #include<stdlib.h> True
Condition
3. void main () break;
within loop
4. {
5. int i;
6. for(i = 0; i<10; i++)
False
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output:
0 1 2 3 4 5 came outside of loop i = 5
Example:
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
43 | C P R O G R A M M I N G L A N G U A G E
Output:
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
C continue statement
The continue statement in C language is used to bring the program control
to the beginning of the loop. The continue statement skips some lines of
code inside the loop and continues with the next iteration. It is mainly used
for a condition so that we can skip some code for a particular condition.
Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped
Example:
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
44 | C P R O G R A M M I N G L A N G U A G E
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }
Output:
infinite loop
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output:
1
2
3
4
6
7
8
9
10
45 | C P R O G R A M M I N G L A N G U A G E
C Functions
In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed
by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection
of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
Function Aspects
There are three aspects of a C function.
SN c function syntax
aspect
1 Function return_type function_name (argument list);
declaration
2 Function call function_name (argument_list)
3 Function return_type function_name (argument list)
definition {function body;}
Types of Functions
There are two types of functions in C programming:
Return Value
A C function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from
the function.
1. void hello(){
2. printf("hello c");
3. }
1. float get(){
2. return 10.2;
3. }
48 | C P R O G R A M M I N G L A N G U A G E
Now, you need to call the function, to get the value of the function.
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Sau prakashani");
11. }
Output:
Hello Sau prakashani
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
49 | C P R O G R A M M I N G L A N G U A G E
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output:
Going to calculate the sum of two numbers:
The sum is 34
Output:
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at
a common place called the library. Such functions are used to perform some
specific operations. For example, printf is a library function used to print on
the console. The library functions are created by the designers of compilers.
All C standard library functions are defined inside the different header files
saved with the extension .h. We need to include these header files in our
program to make use of the library functions defined in such header files.
For example, To use the library functions such as printf/scanf we need to
include stdio.h in our program which is a header file that contains all the
library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
4 Stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc
5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.
9 signal.h All the signal handling functions are defined in this header
file.
Call by value in C
o In call by value method, the value of the actual parameters is copied
into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
52 | C P R O G R A M M I N G L A N G U A G E
o In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
o In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
o The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the
function definition.
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
1. #include<stdio.h>
53 | C P R O G R A M M I N G L A N G U A G E
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by reference in C
o In call by reference, the address of the variable is passed into the
function call as the actual parameter.
o The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
o In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function
54 | C P R O G R A M M I N G L A N G U A G E
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // pr
inting the value of a and b in main
55 | C P R O G R A M M I N G L A N G U A G E
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The val
ues of actual parameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b)
; // Formal parameters, a = 20, b = 10
18. }
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Recursion in C
Recursion is the process which comes into existence when a function calls a
copy of itself to work on a smaller problem. Any function which calls itself is
called recursive function, and such function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is
important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the
tasks that can be defined in terms of similar subtasks. For Example,
recursion may be applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function
call is always overhead. Any problem that can be solved recursively, can also
be solved iteratively. However, some problems are best suited to be solved
56 | C P R O G R A M M I N G L A N G U A G E
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10.}
11.int fact(int n)
12.{
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25.}
Output:
Enter the number whose factorial you want to calculate?5
factorial = 120
57 | C P R O G R A M M I N G L A N G U A G E
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10.}
11.int fibonacci (int n)
12.{
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25.}
Output:
Enter the value of n?12
144
58 | C P R O G R A M M I N G L A N G U A G E
C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection
of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed
by using its index number.
By using the array, we can access the elements easily. Only a few lines of
code are required to access the elements of the array.
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same
size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations
where the first element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can
calculate the address of each element of the array with the given base
address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements
of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines
of code only.
59 | C P R O G R A M M I N G L A N G U A G E
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the
array, we can't exceed the limit. So, it doesn't grow the size dynamically like
LinkedList which we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element.
We can initialize each element of the array by using the index. Consider the
following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
60 | C P R O G R A M M I N G L A N G U A G E
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10.//traversal of array
11.for(i=0;i<5;i++){
12.printf("%d \n",marks[i]);
13.}//end of for loop
14.return 0;
15.}
Output
80
60
70
85
75
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also
be written as the following code.
int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C.
1. #include<stdio.h>
2. int main(){
61 | C P R O G R A M M I N G L A N G U A G E
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
62 | C P R O G R A M M I N G L A N G U A G E
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28.}
data_type array_name[rows][columns];
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the
declaration and initialization are being done simultaneously. However, this
will not work with 2D arrays. We will have to define at least the second
dimension of the array. The two-dimensional array can be declared and
defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
64 | C P R O G R A M M I N G L A N G U A G E
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
1. #include<stdio.h>
2. void main ()
3. {
65 | C P R O G R A M M I N G L A N G U A G E
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Output:
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
66 | C P R O G R A M M I N G L A N G U A G E
avg = sum / n;
printf("Average = %.2f", avg);
return 0;
}
Output
return 0;
}
Output
C Pointers
Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
Pointer Syntax
Here is how we can declare pointers.
int* p;
Here, we have declared a pointer p of int type.
You can also declare pointers in these ways.
int *p1;
69 | C P R O G R A M M I N G L A N G U A G E
int * p2;
Let's take another example of declaring pointers.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable.
Let's take a working example.
#include<stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
Note: You will probably get a different address when you run the above
code.
Assigning addresses to Pointers
Let's take an example.
int* pc, c;
c = 5;
pc = &c;
Here, 5 is assigned to the c variable. And, the address of c is assigned to the
pc pointer.
Get Value of Thing Pointed by Pointers
To get the value of the thing pointed by the pointers, we use the * operator.
For example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc); // Output: 5
Here, the address of c is assigned to the pc pointer. To get the value stored
in that address, we used *pc.
Note: In the above example, pc is a pointer, not *pc. You cannot and should
not do something like *pc = &c;
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
We have assigned the address of c to the pc pointer.
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is
the same, c will be equal to 1.
int* pc, c, d;
c = 5;
72 | C P R O G R A M M I N G L A N G U A G E
d = -15;
#include<stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
73 | C P R O G R A M M I N G L A N G U A G E
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
Relationship Between Arrays and Pointers
An array is a block of sequential data. Let's write a program to print
addresses of array elements.
#include<stdio.h>
int main() {
int x[4];
int i;
74 | C P R O G R A M M I N G L A N G U A G E
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
There is a difference of 4 bytes between two consecutive elements of array
x. It is because the size of int is 4 bytes (on our compiler).
Notice that, the address of &x[0] and x is the same. It's because the
variable name x points to the first element of the array.
From the above example, it is clear that &x[0] is equivalent to x. And, x[0]
is equivalent to *x.
Similarly,
&x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
&x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
...
Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).
75 | C P R O G R A M M I N G L A N G U A G E
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29
Here, we have declared an array x of 6 elements. To access elements of the
array, we have used pointers.
Example 2: Arrays and Pointers
#include<stdio.h>
int main() {
76 | C P R O G R A M M I N G L A N G U A G E
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2
In this example, &x[2], the address of the third element, is assigned to the
ptr pointer. Hence, 3 was displayed when we printed *ptr.
And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-
1) gives us the second element.
Example: Passing Pointers to Functions
#include<stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
77 | C P R O G R A M M I N G L A N G U A G E
addOne(p);
printf("%d", *p); // 11
return 0;
}
Here, the value stored at p, *p, is 10 initially.
We then passed the pointer p to the addOne() function. The ptr pointer gets
this address in the addOne() function.
C Strings
char s[5];
78 | C P R O G R A M M I N G L A N G U A G E
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
Here, we have used fgets() function to read a string from the user.
#include<string.h>
Note: You have to include the code below to run string handling functions.