0% found this document useful (0 votes)
2 views47 pages

C Programming

The document provides an overview of the C programming language, highlighting its significance as a foundational language for modern programming. It covers various aspects including its classification as a mother language, system programming language, and its features such as simplicity, portability, and memory management. Additionally, it discusses key concepts like variables, data types, operators, and the compilation process.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views47 pages

C Programming

The document provides an overview of the C programming language, highlighting its significance as a foundational language for modern programming. It covers various aspects including its classification as a mother language, system programming language, and its features such as simplicity, portability, and memory management. Additionally, it discusses key concepts like variables, data types, operators, and the compilation process.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

C Programming:

Important Question and answer:

The C Language is developed by Dennis Ritchie

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language

1
4. Structured programming language
5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.

2) C as a system programming language


C language is a system programming language because it can be used to do low-level
programming (for example driver and kernel). It is generally used to create hardware devices,
OS, drivers, kernels, etc. For example, Linux kernel is written in C.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

4) C as a structured programming language


A structured programming language is a subset of the procedural language. Structure means
to break a program into parts or blocks so that it may be easy to understand.

In the C language, we break the program into parts using functions. It makes the program easier
to understand and modify.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both low-level
and high-level languages. C language program is converted into assembly code, it supports
pointer arithmetic (low-level), but it is machine independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is machine


dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.

2
Features of C Language
C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. 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.)
7. Fast Speed
8. Pointers
9. Recursion (It provides code reusability for every function. Recursion enables us to
use the approach of backtracking.)
10. Extensible (can easily adopt new features.)

#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .

int main() The main() function is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

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.

What is a compilation?
The compilation is a process of converting the source code into object code or machine code.
It is done with the help of the compiler. The compiler checks the source code for the syntactical
or structural errors, and if the source code is error-free, then it generates the object code or
machine code.

3
The following are the phases through which our program passes before being transformed into
an executable form:

o Preprocessor
o Compiler
o Assembler
o Linker

Assembler

The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.

Linker
The main working of the linker is to combine the object code of library files with the object code
of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the object
code of our program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the source file but

4
differs only in their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX,
the executable file can be named as 'a.out'.

Let's understand through an example.

hello.c

#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}

Now, we will create a flow diagram of the above program:

5
6
printf() and scanf() in C
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

Variables in C
A Variable is a name given that is assigned to a memory location, which is used to contain the
corresponding value in it.

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a
digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable

7
}

You must have to initialize the local variable before it is used.

Global Variable
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}

Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.

void main(){
int x=10;//local variable (also automatic)

8
auto int y=20;//automatic variable
}

External Variable
We can share a variable in multiple C source files by using an external variable. To declare an
external variable, you need to use extern keyword.

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Keywords in C
A keyword is a reserved word that has special meaning to compiler. You cannot use it as a
variable name, constant name, etc. There are only 32 reserved words (keywords) in the C
language.

C Identifiers
Identifier is the name give to a variable, function, structure, array etc. There is a total of 63
alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers

9
o The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Types of identifiers
o Internal identifier
o External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variable

Differences between Keyword and Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and uppercase
letters.

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical It is a combination of alphanumeric characters.


characters.

It does not contain the underscore character. It can contain the underscore character.

10
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

1. Arithmetic Operators
2. Relational Operators
3. Shift Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary or Conditional Operators
7. Assignment Operator
8. Misc Operator

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.

1. Single Line Comments


2. Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\.

Mult Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code,
but it can't be nested

11
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.

The commonly used format specifiers in printf() function are:

Format Description
specifier

%d or %i It is used to print the signed integer value where signed integer means that the variable
can hold both positive and negative values.

%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.

%o It is used to print the octal unsigned integer where octal integer value always starts with
a 0 value.

%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer
value always starts with a 0x value. In this, alphabetical characters are printed in small
letters such as a, b, c, etc.

%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.

%f It is used for printing the decimal floating-point values. By default, it prints the 6 values
after '.'.

%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.

%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e.,
the value after the decimal in input would be exactly the same as the value in the
output.

%p It is used to print the address in a hexadecimal form.

%c It is used to print the unsigned character.

%s It is used to print the strings.

%ld It is used to print the long-signed integer value.

12
Minimum Field Width Specifier
Suppose we want to display an output that occupies a minimum number of spaces
on the screen. You can achieve this by displaying an integer number after the
percent sign of the format specifier.

int main()
{
int x=900;
printf("%8d", x);
printf("\n%-8d",x);
return 0;
}

Now we will see how to fill the empty spaces. It is shown in the below code:

int main()
{
int x=12;
printf("%08d", x);
return 0;
}

In the above program, %08d means that the empty space is filled with zeroes.
13
Specifying Precision
We can specify the precision by using '.' (Dot) operator which is followed by integer
and format specifier.

int main()
{
float x=12.2;
printf("%.2f", x);
return 0;
}

14
Constants in C
A constant is a value or variable that can't be changed in the program, for example:
10, 20, 'a', 3.4, "c programming" etc.

2 ways to define constant in C


There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.

const float PI=3.14;

Now, the value of PI variable can't be changed.

#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

#include<stdio.h>
int main(){
const float PI=3.14;
PI=4.5;

15
printf("The value of PI is: %f",PI);
return 0;
}

Output:

Compile Time Error: Cannot modify a const object

C #define
The #define preprocessor directive is used to define constant or micro substitution.
It can use any basic data type.

Syntax:

#define token value

Let's see an example of #define to define a constant.

#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}

Output:

3.140000

Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We
can define the token as the smallest individual element in C. For `example, we
cannot create a sentence without using words; similarly, we cannot create a program

16
in C without using tokens in C. Therefore, we can say that tokens in C is the building
block or the basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

1. Keywords in C
2. Identifiers in C
3. Strings in C
4. Operators in C
5. Constant in C
6. Special Characters in C

Strings in C

Strings in C are always represented as an array of characters having null character


'\0' at the end of the string. This null character denotes the end of the string. Strings
in C are enclosed within double quotes, while characters are enclosed within single
characters. The size of a string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of


characters.

Special characters in C

Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single
and multidimensional subscripts.

17
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single
printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.

C Boolean
In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically,
the bool type value represents two types of behavior, either true or false. Here, '0'
represents false value, while '1' represents true value.

In C Boolean, '0' is stored as 0, and another integer is stored as 1. We do not require


to use any header file to use the Boolean data type in C++, but in C, we have to use
the header file, i.e., stdbool.h. If we do not use the header file, then the program will
not compile.

Syntax
bool variable_name;

In the above syntax, bool is the data type of the variable, and variable_name is the
name of the variable.

Let's understand through an example.

#include <stdio.h>
#include<stdbool.h>
int main()

18
{
bool x=false; // variable initialization.
if(x==true) // conditional statements
{
printf("The value of x is true");
}
else
printf("The value of x is FALSE");
return 0;
}

Static in C
Static is a keyword used in C programming language. It can be used with both
variables and functions, i.e., we can declare a static variable and static function as
well. An ordinary variable is limited to the scope in which it is defined, while the
scope of the static variable is throughout the program.

Static keyword can be used in the following situations:


o Static global variable
When a global variable is declared with a static keyword, then it is known as a
static global variable. It is declared at the top of the program, and its visibility
is throughout the program.
o Staticfunction
When a function is declared with a static keyword known as a static function.
Its lifetime is throughout the program.
o Static local variable
When a local variable is declared with a static keyword, then it is known as a
static local variable. The memory of a static local variable is valid throughout
the program, but the scope of visibility of a variable is the same as the
automatic local variables. However, when the function modifies the static local

19
variable during the first function call, then this modified value will be available
for the next function call also.

Static Function
As we know that non-static functions are global by default means that the function
can be accessed outside the file also, but if we declare the function as static, then it
limits the function scope. The static function can be accessed within a file only.

The static function would look like as:

static void func()


{
printf("Hello javaTpoint");
}

Differences b/w static and global variable


Global variables are the variables that are declared outside the function. These
global variables exist at the beginning of the program, and its scope remains till the
end of the program. It can be accessed outside the program also.

Static variables are limited to the source file in which they are defined, i.e., they are
not accessible by the other source files.

Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the
behavior of the program abnormal, and experienced developers can also make these
faults. Programming errors are also known as the bugs or faults, and the process of
removing these bugs is known as debugging.

These errors are detected either during the time of compilation or execution. Thus,
the errors must be removed from the program for the successful execution of the
program.

20
There are mainly five types of errors exist in C programming:

o Syntax error or Compilation Error


o Run-time error
o Linker error
o Logical error
o Semantic error

Syntax error
Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the compilers.
These errors are mainly occurred due to the mistakes while typing or do not follow
the syntax of the specified programming language.

For example:

If we want to declare the variable of type integer,


int a; // this is the correct form
Int a; // this is an incorrect form.

Commonly occurred syntax errors are:

o If we miss the parenthesis (}) while writing the code.


o Displaying the value of a variable without its declaration.
o If we miss the semicolon (;) at the end of the statement.

Let's understand through an example.

#include <stdio.h>
int main()
{
a = 10;
printf("The value of a is : %d", a);
return 0;

21
}

Run-time error
Sometimes the errors exist during the execution-time even after the successful
compilation known as run-time errors. When the program is running, and it is not
able to perform the operation is the main cause of the run-time error. The division
by zero is the common example of the run-time error. These errors are very difficult
to find, as the compiler does not point to these errors.

Let's understand through an example.

#include <stdio.h>
int main()
{
int a=2;
int b=2/0;
printf("The value of b is : %d", b);
return 0;
}

Logical error
The logical error is an error that leads to an undesired output. These errors produce
the incorrect output, but they are error-free, known as logical errors. These types of
mistakes are mainly done by beginners. The occurrence of these errors mainly
depends upon the logical thinking of the developer. If the programmers sound
logically good, then there will be fewer chances of these errors.

Let's understand through an example.

#include <stdio.h>
int main()
{
int sum=0; // variable initialization
int k=1;
for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop

22
{
sum=sum+k;
k++;
}
printf("The value of sum is %d", sum);
return 0;
}

In the above code, we are trying to print the sum of 10 digits, but we got the wrong
output as we put the semicolon (;) after the for loop, so the inner statements of the
for loop will not execute. This produces the wrong output.

Semantic error
Semantic errors are the errors that occurred when the statements are not
understandable by the compiler.

The following can be the cases for the semantic error:

o Use of a un-initialized variable.


int i;
i=i+2;
o Type compatibility
int b = "javatpoint";
o Errors in expressions
int a, b, c;
a+b = c;

23
o Array index out of bound
int a[10];
a[10] = 34;

Let's understand through an example.

#include <stdio.h>
int main()
{
int a,b,c;
a=2;
b=3;
c=1;
a+b=c; // semantic error
return 0;
}

In the above code, we use the statement a+b =c, which is incorrect as we cannot use
the two operands on the left-side.

Compile time vs Runtime


Compile-time is the time at which the source code is converted into an
executable code while the run time is the time at which the executable code is
started running. Both the compile-time and runtime refer to different types of error.

The compile-time errors can be:

o Syntax errors
o Semantic errors

Runtime errors
The runtime errors are the errors that occur during the execution and after
compilation. The examples of runtime errors are division by zero, etc. These errors
are not easy to detect as the compiler does not point to these errors.

24
Let's look at the differences between compile-time and runtime:

Compile-time Runtime

The compile-time errors are the errors The runtime errors are the errors which
which are produced at the compile-time, are not generated by the compiler and
and they are detected by the compiler. produce an unpredictable result at the
execution time.

In this case, the compiler prevents the In this case, the compiler does not detect
code from execution if it detects an error the error, so it cannot prevent the code
in the program. from the execution.

It contains the syntax and semantic It contains the errors such as division by
errors such as missing semicolon at the zero, determining the square root of a
end of the statement. negative number.

Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional
statements are the decision-making statements which depends upon the output of
the expression. It is represented by two symbols, i.e., '?' and ':'.

Syntax of a conditional operator


Expression1? expression2: expression3;

Let's understand the ternary or conditional operator through an example.

#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // cond
itional operator
25
return 0;
}

Let's understand this scenario through an example.

#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}

Bitwise AND operator


Bitwise AND operator is denoted by the single ampersand sign (&). Two integer
operands are written on both sides of the (&) operator. If the corresponding bits of
both the operands are 1, then the output of the bitwise AND operation is 1;
otherwise, the output would be 0.

For example,

We have two variables a and b.


a =6;
b=4;
The binary representation of the above two variables are given below:
a = 0110
b = 0100
When we apply the bitwise AND operation in the above two variables, i.e., a&b, the o
utput would be:
Result = 0100

26
As we can observe from the above result that bits of both the variables are
compared one by one. If the bit of both the variables is 1 then the output would be
1, otherwise 0.

Let's understand the bitwise AND operator through the program.

#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}

In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a'
and 'b' are 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110,
respectively. When we apply the AND operator between these two variables,

a AND b = 0110 && 1110 = 0110

Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer
operands are written on both sides of the (|) symbol. If the bit value of any of the
operand is 1, then the output would be 1, otherwise 0.

For example,

We consider two variables,

27
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the
output would be:
Result = 0001 1111

As we can observe from the above result that the bits of both the operands are
compared one by one; if the value of either bit is 1, then the output would be 1
otherwise 0.

Let's understand the bitwise OR operator through a program.

#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}

28
Control Statements:
If-Else (Javatpoint)

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 possible values of a single variable
called switch variable. Here, We can define various statements in the multiple cases
for the different values of a single variable.

The syntax of switch statement in c language is given below:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Rules for switch statement in C language


1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

29
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched
case. It is known as fall through the state of C switch statement.

5) A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of
the cases is true. No break is needed in the default case.

Let's try to understand it by the examples. We are assuming that there are following
variables.

int x,y,z;
char a,b;
float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;

Let's see a simple example of c language switch statement.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);

30
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Switch case example 2


#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}
}

31
Let's try to understand the fall through state of switch statement by the example
given below.

#include<stdio.h>
int main(){
int number=0;

printf("enter a number:");
scanf("%d",&number);

switch(number){
case 10:
printf("number is equal to 10\n");
case 50:
printf("number is equal to 50\n");
case 100:
printf("number is equal to 100\n");
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Output

enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Output

enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

32
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

C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be
used to repeat some part of the code for a particular condition. It can also be used
to break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable
and complecated.

Syntax:

label:
//some part of the code;
goto label;

goto example
Let's see a simple example to use goto statement in C language.

33
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast
operator for typecasting which is denoted by (type).

Syntax:

(type)value;

Without Type Casting:

int f= 9/4;
printf("f : %d\n", f );//Output: 2

With Type Casting:

float f=(float) 9/4;


printf("f : %f\n", f );//Output: 2.250000

Function Aspects
There are three aspects of a C function.
34
o Function declaration A function must be declared globally in a c program to
tell the compiler about the function name, function parameters, and return
type.
o Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
o Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes when
the function is called. Here, we must notice that only one value can be
returned from the function.

SN C function aspects Syntax

1 Function return_type function_name (argument list);


declaration

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function


body;}

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity
of a big program and optimizes the code.

Return Value
35
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.

Example without return value:

void hello(){
printf("hello c");
}

36
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.

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.
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.

37
Let's try to understand the concept of call by value in c language by the example
given below:

#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

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

Call by Value Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the
value of a and b in main
swap(a,b);

38
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actua
l parameters do not change by changing the formal parameters in call by value, a =
10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parame
ters, a = 20, b = 10
}

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 are
performed on the value stored at the address of the actual parameters, and
the modified value gets stored at the same address.

#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);

39
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}

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

Call by reference Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the
value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actu
al parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal para
meters, a = 20, b = 10
40
}

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

Difference between call by value and call by reference


in c

No. Call by value Call by reference

1 A copy of the value is passed into the An address of value is passed into the
function function

2 Changes made inside the function is Changes made inside the function
limited to the function only. The validate outside of the function also.
values of the actual parameters do The values of the actual parameters
not change by changing the formal do change by changing the formal
parameters. parameters.

3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory location
location

Passing an array to a function


Passing array to a function
#include <stdio.h>
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}

41
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}

Passing array to a function as a pointer

Now, we will see how to pass an array to a function as a pointer.

#include <stdio.h>
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}

42
C Pointers
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of
the pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.

Consider the following example to define a pointer which stores the address of an
integer.

int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n
of type integer.

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to cha

Pointer Example
An example of using pointers to print the address and value is given below.

43
As you can see in the above figure, pointer variable stores the address of number
variable, i.e., fff4. The value of number variable is 50. But the address of pointer
variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for the above figure.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number the
refore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a
pointer therefore if we print *p, we will get the value stored at the address containe
d by p.
return 0;
}

Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50

44
More Details:
https://www.tutorialspoint.com/cprogramming/c_pointers.htm

Also Follow Javatpoint:

https://www.javatpoint.com/c-pointers

ei link er pointer er sobkichu.

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c
language is possible by 4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while memory can be increased while


executing program. executing program.

used in array. used in linked list.

45
Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

Difference between malloc() and calloc():

46
Difference between Structure and Union:

47

You might also like