C programming note by Rajesh parajuli
C programming note by Rajesh parajuli
+9779847546279
Online C compiler
Variable in c
Type conversion
Control Statements
Conditional / Selective Structure
Looping Structure
Function in c
Call by value & Call by reference
Recursion Function
Array
Difference between Malloc and Calloc
Pointer
String
Structure
Pointer to Structure
File Handling in c
What is Program?
The program is the set of instructions that command the computer to perform a
particular operation or a specific task.
Instruction is a statement.
×
A statement is an instruction to do only one task.
A group of statements is composed together to form a program.
1. Low-level Language
2. High Level Language
Language Translator
Translator is a software that translates or converts instructions written in assembly or
high-level language (Source Code) into Machine language(Object Codes).
The program is developed in assembly or high level language for the easyness,
understandable (Convenience) of the programmer, but the computer does not
understand these statements directly, so translator is used which converts those
statements in a computer execuable format.
Types of Translators
1. Assembler
2. Compiler
3. Interpreter
Assembler: Assembler is a translator that converts the code of the assembly language
(Source code) into the machine executible language machine language (Object Code).
When assembler completed it converted process then only it started to execute the
program.
Compiler: A Compiler is a translator which translates the complete high level program
(Source Code) into the machine code (object code) at once if the program doesn’t
contain syntax errors. Programming languages like C, C++, Java use the compiler.
Compiler Interpreter
Compiler translates the whole program into object Interpreter Translates one line or single statement
code at a time. of a program into object code at a time.
The compiler shows the complete errors and An interpreter reads the program line-by-line; it
warning messages at program compilation time. So shows the error if present at that specific line. You
it is not possible to run the program without fixing must have to correct the error first to interpret the
program errors. Doing debugging of the program is next line of the program. Debugging is
comparatively complex while working with a comparatively easy while working with an
compiler Interpreter.
Examples of compiler based programming language Examples of Interpreter based programming are
are C, C++, Java, COBOL, Pascal, FORTRAN BASIC, C#, PHP
Syntax
In a programming language, Syntax defines the rules that govern the structure and
arrangement of keywords, symbols, and other elements. Syntax doesn’t have any
relationship with the meaning of the statement; it is only associated with the grammar
and structure of the programming language.
A line of code is syntactically valid and correct if it follows all the rules of syntax.
Syntax does not have to do anything with the meaning of the statement.
Syntax errors are easy to catch.
Syntax errors are encountered after the program has been executed
Semantics
Semantics refers to the meaning of the associated line of code and how they are
executed in a programming language. semantics helps interpret what function the line
of code/program is performing.
If there is any semantic error and even when the statement has correct syntax, it
wouldn’t perform the function that was intended for it to do. Thus, such errors are
difficult to catch.
Semantics are encountered at runtime.
Example of an algorithm:
step 1: START
Step5: Stop.
Step1: Start.
Step5: Print SI
Step6: END
Step1: Start.
Step2: Initialize X as 0,
Step3: Increment X by 1,
Step4: Print X,
Step6: Stop.
Flowchart
A flowchart is a pictorial representation of an algorithm. Flowchart is a diagrammatic representation of
sequence of logical steps of a program. Flowcharts use simple geometric shapes to depict processes and
arrows to show relationships and process/data flow.
Used at the beginning and end of the algorithm to show start and
Start/Stop
end of the program.
On-page Connects two or more parts of a flowchart, which are on the same
Connector page.
Off-page Connects two parts of a flowchart which are spread over different
Connector pages.
4. Determine Whether A Student Passed the Exam or Not:
Algorithm
Algorithm Flowchart
It costs more time to create an algorithm. It costs less time to create a flowchart.
Portability
A program should be supported by many different computers. The program should compile and run
smoothly on different platforms. Because of rapid development in hardware and software, platform change
is a common phenomenon these days. So, portability is measured by how a software application can be
transferred from one computer environment to another without failure. A program is said to be more
portable if it is easily adopted on different computer systems. Subsequently, if a program is developed only
for a particular platform, its life expectancy is seriously compromised.
Maintainability
It is the process of fixing program errors and improving the program. If a program is easy to
read and understand, then its maintenance will be easier. It should also prevent unwanted
work so that the maintenance cost in the future will be low. It should also have quality to
easily meet new requirements. A maintainable software allows us to fix bugs quickly and
easily, improve usability and performance, add new features, make changes to support
multiple platforms, and so on.
Efficient
Program is said to be more efficient if it takes the least amount of memory and processing time and is easily
converted to machine language. The algorithm should be more effective. Every program needs a certain
amount of processing time and memory to process the instructions and data. The program efficiency is also
high if it has a high speed during runtime execution of the program.
Reliable
The user’s actual needs will change from time-to-time, so the program is said to be reliable if it works
smoothly in every version. It is measured as reliable if it gives the same performance in all simple to
complex conditions.
Machine Independent
Program should be machine-independent. Program written on one system should be able to execute on
many different types of computers without any changes. It is not system specific and provides more
flexibility. An example of this would be Java.
Cost Effectiveness
Cost Effectiveness is the key to measure the program quality. The cost must be measured over the life of the
program and must include both costs and human costs of producing these programs.
Flexible
The program should be written in such a manner that it allows one to add new features without changing the
existing module. The majority of the projects are developed for a specific period, and they require
modifications from time to time. It should always be ready to meet new requirements. Highly flexible
software is always ready for a new world of possibilities.
Unit-2 Introduction to C
History of C
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories
of AT&T (American Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as
the founder of the c language. C was developed to overcome the problems of previous languages such as
B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features
of previous languages such as B and BCPL.
Today C is the most widely used and popular System Programming Language. Today’s most popular Linux
OS and RDBMS MySQL have been written in C.
Structure of C Program
1. Documentation (Documentation Section)
2. Preprocessor Statements (Link Section)
3. Definition Section
4. Global Declarations Section
5. Main functions section
6. User-Defined Functions or Sub program functions
In C language, all these six sections together make up the Basic Structure of C Program
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
In addition to all these Header Files in the Link Section, there are a lot of Header Files which we can link in
our program if needed.
3. Definition Section
The definition of Symbolic Constant is defined in this section, so this section is called Definition
Section. Macros are used in this section.
#define PI 3.14
In the Global Declaration section, we also declare functions that we want to use anywhere in our program,
and such functions are called Global Function.
The code we write inside the main() function consists of two parts, one Declaration Part and the other
Execution Part. In the Declaration Part, we declare the variables that we have to use in the Execution Part,
let’s understand this with an example.
Any C Program can be divided into header, main() function, variable declaration, body, and return type of the
program.
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf(“Sum: %d”, sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Sections Description
/**
* file: sum.c
* author: you It is the comment section and is part of the description section of the
* description: program to code.
find sum.
*/
#define X 20 This is the definition section. It allows the use of constant X in the code.
int main() main() is the first function that is executed in the C program.
{…} These curly braces mark the beginning and end of the main function.
printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));
We have used int as the return type so we have to return 0 which states
return 0; that the given program is free from the error and it can be exited
successfully.
int sum(int y)
{ This is the subprogram section. It includes the user-defined functions that
return y + X; are called in the main() function.
}
Write a C program to implement subtraction by giving two numbers from user inputs.
{
int num1, num2, difference;
Character Set
As every language contains a set of characters used to construct words, statements, etc., C language also
has a set of characters which include alphabets, digits, and special symbols. C language supports a total of
256 characters. Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.
Every C program contains statements. These statements are constructed using words and these words are
constructed using characters from C character set. C language character set contains the following set of
characters
1. Alphabets
2. Digits
3. Special Symbols
Alphabets:
C language supports all the alphabets from the English language. Lower and upper case letters together support
52 alphabets.
Digits: C language supports 10 digits which are used to construct numerical values in C language.
Digits – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols:
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Token in C
A token is a smallest individual element of a program which is meaningful to the compiler. The compiler that
breaks a program into the smallest units is called tokens and these tokens proceed to the different stages of
the compilation.
Tokens in C are building blocks which means a program can’t be created without tokens.
1.Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as an identifier.
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords
allowed in ANSI C.
C predefined Keywords
do if static while
2.Identifiers
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-
defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the
starting letter should be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules
for constructing identifiers in C are given below:
An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters and digits) and
underscore( _ ) symbol.
Identifier names must be unique.
The first character must be an alphabet or underscore.
You cannot use a keyword as an identifier.
Only the first thirty-one (31) characters are significant.
It must not contain white spaces.
Identifiers are case-sensitive.
For Example:
int cprogram;
Char Bicte_firstsemester;
here, int and Char is keywords and cprogram and Bicte_firstsemester is identifier.
3.Constants
The constants in C are the read-only variables whose values cannot be modified once they are declared in
the C program. The type of constant can be an integer constant, a floating pointer constant, a string
constant, or a character constant. In C language, the const keyword is used to define the constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is
declared in the program. We can not make any change in the value of the constant
variables after they are defined.
int main()
{
return 0;
}
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
4.Strings
If you follow the rule of array initialization then you can write the above statement as
follows −
#include <stdio.h>
int main () {
#include <stdio.h>
int main()
{
char name[6];
printf(“Enter name: “);
scanf(“%s”, name);
printf(“Your name is %s.”, name);
return 0;
}
Like many other programming languages, strings in C are enclosed within double quotes(” “), whereas
characters are enclosed within single quotes(‘ ‘). When the compiler finds a sequence of characters
enclosed within the double quotation marks, it adds a null character (\0) at the end by default.
char variable[array_size];
5.Special Symbols
Special Symbols are symbols in C language that have special meaning and can not be used for any other
purpose.
Brackets[]: Opening and closing brackets are used as array element references. These indicate single
and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code containing
more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating parameters in function
calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler
to transform your program before actual compilation.
Period (.): Used to access members of a structure or union.
Tilde(~): Used as a destructor to free some space from memory.
Square Brackets [ ]
The opening and closing square brackets represent single and multi-dimensional subscripts and
they are used as array element reference for accessing array elements.
int arr[10]; //For declaring array, with size defined in square brackets
Simple Brackets ( )
The opening and closing circular brackets are used for function calling and function declaration.
get_area(100); //Function calling with 100 as parameter passed in circular brackets
Curly Braces { }
In C language, the curly braces are used to mark the start and end of a block of code containing
executable logical statements.
int main{
printf(“Illustrating the use of curly braces!”);
}
Comma (,)
Commas are used to separate variables or more than one statement just like separating function
parameters in a function call.
int a=10,b=20,c=30; //Use of comma operator
Pre-Processor / Hash (#)
It is a macro-processor that is automatically used by the compiler and denotes that we are using a header
file.
#include<stdio.h> //For defining header-file
#define ll long
int main(){
printf(“Hello World!”);
}
Asterisk (*)
Asterisk symbols can be used for multiplication of variables and also for creating pointer
variables. Example:
int main(){
int a = 20,b = 10;
int sum = a*b; //Use of asterisk in multiplication
int *ptr = &a;
//Pointer variable ptr pointing to address of integer variable a
}
Tilde (~)
It is used as a destructor to free some space from the memory.
int main(){
int n = 2;
printf(“Bitwise complement of %d: %d”, n, ~n);
//Bitwise complement of 2 can be found with the help of tilde operator and the result here is -3
}
Period (.)
It is used to access members of a structure or a union.
#include <stdio.h>
#include <string.h>
int main(){
person1.city_no = 100;
//accessing members of structure using period (.) operator
person1.salary = 200000;
printf(“City_Number: %d”,person1.city_no);
printf(“\nSalary: %.2f”,person1.salary);
return 0;
}
Colon (:)
It is used as a part of conditional operator ( ? : ) in C language.
Example:
Semicolon (;)
It is known as a statement terminator and thus, each logical statement of C language must be ended with a
semi-colon.
Example:
int a = 10, b = 20; //Assignment operator is used to assign some values to the variables
6.operators
Operators are symbols that are used to perform some operation or a set of operations on a variable or a set
of variables. C has a set of operators to perform specific mathematical and logical computations on
operands. C Supports a rich set of built-in Operators. Operators are used to perform operations
on variables and values.
Example: Y= a+b
=, + are operator
a, b are operand
Types of Operator:
1. on the basis of the number of operands required for an operator
2. On the basis of utility or functions of an operator
Binary Operators: The operators which require two operands are known as binary operators. For example:
A+B, A-B, A*B, A/B etc.
Ternary Operators: The operators that require three operands are known as ternary operators. For Example:
A ? B : C (this is also a condiotional operator).
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C
program. They can be used in programs to define expressions and mathematical formulas.
Operator Name of the Arithmetic Operation
Syntax
Operator
+ Addition x+y
Add two operands.
– Subtraction x–y
Subtract the second operand from the first operand.
* Multiplication x*y
Multiply two operands.
/ Division x/y
Divide the first operand by the second operand.
% Modulus division Calculate the remainder when the first operand is divided by x%y
the second operand.
int main()
{
int a = 10, b = 4, res;
// printing a and b
printf(“a is %d and b is %d\n”, a, b);
res = a + b; // addition
printf(“a + b is %d\n”, res);
res = a – b; // subtraction
printf(“a – b is %d\n”, res);
res = a * b; // multiplication
printf(“a * b is %d\n”, res);
res = a / b; // division
printf(“a / b is %d\n”, res);
res = a % b; // modulus
printf(“a %% b is %d\n”, res);
return 0;
}
> Greater than x>y Returns 1 if the first value is greater than the second value
< Less than x<y Returns 1 if the first value is less than the second value
Greater than or Returns 1 if the first value is greater than, or equal to, the
>= x >= y
equal to second value
Less than or equal Returns 1 if the first value is less than, or equal to, the
<= x <= y
to second value
int main()
{
int a = 10, b = 4;
// equal to
if (a == b)
printf(“a is equal to b\n”);
else
printf(“a and b are not equal\n”);
// not equal to
if (a != b)
printf(“a is not equal to b\n”);
else
printf(“a is equal b\n”);
return 0;
}
Logical operators
Logical Operators are used to compare or evaluate logical and relational expressions. The operands of
logical operators must be either Boolean value (1 or 0) or expressions that produces Boolean value. The
Output of these operators is always either 1 true or 0 False. The logical Operators supported in C are :
&& logical AND : it produces true if each operand is true otherwise it produces false.
|| Logical OR : it produces true when any of the conditions is true.
! Logical NOT- it reverse to the operand.
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10, b=5, c=40;
printf(“a<b && a<c is %d\n”, (a<b && a<c));
printf(“a>b && b>c is %d\n”, (a>b && b<c));
printf(“a<b || a<c is %d\n”, (a<b || a<c));
printf(“a>b || b<c is %d\n”, (a>b || b<c));
printf(“a>c || b>c is %d\n”, (a>c || b>c));
getch();
return 0;
}
Assignment operators
Assignment Operators are also binary operators and they are used to assign result of an expression to a
variable. The mostly used assignment operator is ‘=’. There are other shorthand assignment operators
supported by C. They are +=, -=, *=, /+ and %=. These Operators are also known as arithmetic assignment
operators.
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10, b=5;
b+=a; //b=b+a
printf(“b=%d”, b);
getch();
return 0;
}
Output:
b=15
++ variable
variable++
–variable
variable++
Conditional Operators
The Operator named “?:” is known as conditional Operator. It takes three operands. Thus, it is also called
ternary operator. The syntax is :
working principal
If(expression 1)
variable = expression2;
else
variable = expression3;
Write a program to read two numbers from user and determine the larger number using conditional
operator.
#include<stdio.h>
#include<conio.h>
int main()
{
int n1, n2, larger;
printf(“Enter two numbers:”);
scanf(“%d%d”, &n1, &n2);
larger = n1>n2 ? n1: n2;
Printf(“The larger number is %d”, larger);
getch();
return 0;
}
Output:
Enter two numbers: 35 90
The larger number is 90
Bitwise Operator
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we
perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits,
either 0 or 1. It is mainly used in numerical computations to make the calculations faster. It can be used only
integer type values not float, double etc.
We have different types of bitwise operators in the C programming language. The following is the list of the
bitwise operators:
| Bitwise OR operator
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise exclusive operator gives 0 if both corresponding values are same. if both corresponding vales are
not same , it gives 1.
#include<stdio.h>
int main()
{
int a=7,b=14;
printf(“Bitwise AND %d\n”, a&b);
printf(“Bitwise OR %d\n”, a|b);
printf(“Bitwise XOR %d\n”, a^b);
return 0;
}
Output:
Bitwise AND 6
Bitwise OR 15
Bitwise XOR 9
The left shift operator is a type of Bitwise shift operator, which performs operations on the binary bits. It is a
binary operator that requires two operands to shift or move the position of the bits to the left side and add
zeroes to the empty space created at the right side after shifting the bits.
Bitwise Left shift operator is used to shift the binary sequence to the left side by specified position.
Example
Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8 bit)
14 = (00001110) 2
Then 14 << 1 will shift the binary sequence 1 position to the left side.
Like,
#include <stdio.h>
int main ()
{
// declare local variable
int num;
printf (” Enter a positive number: “);
scanf (” %d”, &num);
// use left shift operator to shift the bits
num = (num << 2); // It shifts two bits at the left side
printf (” \n After shifting the binary bits to the left side. “);
printf (” \n The new value of the variable num = %d”, num);
return 0;
}
Enter a positive number: 14
After shifting the binary bits to the left side.
The new value of the variable num = 56
In general, if we shift a number by n position to left, the output will be number * (2n).
Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.
Example
Let’s take a number 14.
Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8 bit)
14 = (00001110) 2
Then 14 >> 1 will shift the binary sequence by 1 position to the right side.
In general, if we shift a number by n times to right, the output will be number / (2n) .
1. #include <stdio.h>
2. int main ()
3. {
4. // declare local variable
5. int num;
6. printf (” Enter a positive number: “);
7. scanf (” %d”, &num);
8. // use right shift operator to shift the bits
9. num = (num >> 2); // It shifts two bits at the right side
10. printf (” \n After shifting the binary bits to the right side. “);
11. printf (” \n The new value of the variable num = %d”, num);
12. return 0;
13. }
Output:
Variable
Variable is a container that holds the value of any kind of data type. It is a case sensitive in c program. It is
an identifier which store the value and reserved some memory space for data of any type.
Syntax:
data_type variable_name=value;
Example
#include <stdio.h>
int main() {
int x = 5;// x is a variable of integer type
char y[12] = “helloworld”;// y is a variable of string type
char z=’b’; // z is a variable of character type
float a=12.5; // a is a variable of float type
double b=19.99; // b is a variable of double type
printf(“%d\n%s\n%c\n%f\n%lf\n”, x,y,z,a,b);
return 0;
}
Output:
5
helloworld
b
12.500000
19.990000
Data
Size Description
Type
2
short Stores whole numbers from -32,768 to 32,767
bytes
4
int Stores whole numbers from -2,147,483,648 to 2,147,483,647
bytes
4
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
bytes
8
double Stores fractional numbers. Sufficient for storing 15 decimal digits
bytes
2
char Stores a single character/letter or ASCII values
bytes
Type conversion
Type conversion is the way of converting a datatype of one variable to another datatype.
1. Implicit type conversion- conversion is done by the compiler and there is no loss of information. It is
automatic type conversion.
2. Explicit type conversion- conversion is done by the programmer and there will be loss of information.
int main()
{
double x = 1.2
int y=5;
int sum;
return 0;
}
output:6
Control Statements in c
Control Statements control the flow of execution of the statements of a program. The various types of
Control statements are :
1. Conditional Statements
In conditional control , the execution of statements depends upon the condition-test. If the condition
evaluates to true, then a set of statements is executed otherwise another set of statements is followed. This
control is also called Decision Control or selective control statement because it helps in making decision
about which set of statements is to be executed.
If statement: This is the most simple form of decision control statement. In this form, a set of statements
are executed only if the condition given with if evaluates to true.
Syntax:
if(condition)
{
//if block of Statements executed if the given if condition is true ;
}
If else Statement: This is a bi-directional control statement. This statement is used to test a condition and
take one of the two possible actions. If the condition evaluates to true then one statement (or block of
statements) is executed otherwise other statement (or block of statements) is executed.
Syntax:
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
//executed outer statements;
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there
are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is
true then the statements defined in the if block will be executed, otherwise if some other condition is true
then the statements defined in the else-if block will be executed, at the last if none of the condition is true
then the statements defined in the else block will be executed. There are multiple else-if blocks possib
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
…
else
{
//code to be executed if all the conditions are false
}
//executed outer statements if it is there;
Nested if else: Nested if else statement is a control statement where both if else statement is there with
having another if else statement inside it.
int main() {
return 0;
}
Q. Find greatest number among three numbers using if else laddar statement.
#include <stdio.h>
int main() {
return 0;
}
Q.Find the greatest number among three numbers using nested if else statement.
#include <stdio.h>
int main() {
// outer if statement
if (n1 >= n2) {
// inner if…else
if (n1 >= n3)
printf(“%d is the largest number.”, n1);
else
printf(“%d is the largest number.”, n3);
}
// inner if…else
if (n2 >= n3)
printf(“%d is the largest number.”, n2);
else
printf(“%d is the largest number.”, n3);
}
return 0;
}
Switch case: A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case. The switch
statement allows us to execute one code block among many alternatives.
Syntax:
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;//optional
.
.
.
default:
// default statements
}
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;
case 3:
printf(“Wednesday”);
break;
case 4:
printf(“Thursday”);
break;
case 5:
printf(“Friday”);
break;
case 6:
printf(“Saturday”);
break;
case 7:
printf(“Sunday”);
break;
}
return 0;
}
Conditional operator statement: It is a ternary operator and is used to perform simple conditional operations.
It is used to do operations similar to if-else statement.
Example
#include <stdio.h>
int main() {
int num;
scanf(“%d”, &num);
(num % 2 == 0)? printf(“The given number is even”) : printf(“The given number is odd”);
return 0;
}
1. Write a c program to find greatest number among two numbers using conditional operator
statement.
2. Write a c program to print candidate can vote if candidate age is greater or equal to 18 and print
candidate cannot vote if not greater than equal to age of 18.
1. While loop
2. Do-while loop
3. For loop
While loop: The while loop loops execute a block of code as long as a specified condition is true. It is also
known as entry controlled loop that means the test condition is checked before entering the main body of
the loop.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
Example:
#include <stdio.h>
int main () {
return 0;
}
Do-while loop: The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least
once irrespective of the test condition. In case of do-while, firstly the statements inside the loop body are
executed and then the condition is evaluated. As a result of which this loop is executed at least once even if
the condition is initially false. After that the loop is repeated until the condition evaluates to false. Since in
this loop the condition is tested after the execution of the loop, it is also known as posttest loop. It is also
called exit controlled loop means the means the test condition is evaluated at the end of the loop body.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
#include <stdio.h>
int main() {
int i = 0;
do {
printf(“%d\n”,i);
i++;
}while(i<=5);
return 0;
}
For loop: The for loop allows to execute block of statements for a number of times. when number of
repetitions is known in advance, the use of for loop will be more efficient. Thus this loop is also known as a
determinate or definite loop. For loop consists of three expressions with semicolons.
for(initialization; test_condition; increment or decrement) { Statements or body of loop; }
int main()
{
int num,i;
long fact=1;
printf(“Enter number”);
scanf(“%d”,&num);
for(i=1;i<=num;i++)
fact=fact*i;
printf(“%ld”,fact);
return 0;
}
C program to generate Fibonaci series (most important, will apear in exam question)
#include <stdio.h>
int main() {
int i, n;
return 0;
}
Nested Loop
Nested loop: Using a loop inside another loop is called nested loop. C support n times of nested loop. The
nested for loop means any type of loop which is defined inside the ‘for’ loop.
First, the ‘i’ variable is initialized to 1 and then program control passes to the
i<=n.
The program control checks whether the condition ‘i<=n’ is true or not.
If the condition is true, then the program control passes to the inner loop.
The inner loop will get executed until the condition is true.
After the execution of the inner loop, the control moves back to the update of
the outer loop, i.e., i++.
After incrementing the value of the loop counter, the condition is checked again,
i.e., i<=n.
If the condition is true, then the inner loop will be executed again.
This process will continue until the condition of the outer loop is true.
3. Jump Statements
Jump statements in C are used to alter the normal sequence of execution of a program. They allow the
program to transfer control to a different part of the code.
Simple definition: Jump statements are used to transfer the control from one part of the program to another
part.
1. break
2. continue
3. goto
4. return
The break Statement terminates the execution of the loop and the control transferred to the statement
immediately following the loop.
Break statement is used inside the loops or switch statement. This statement causes an immediate exit
from the loop or the switch case block in which it appears. If the test condition is to be terminated instantly
without testing termination condition, the break statement is useful.
It can be written as
break;
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=1; i<10; i++)
{
printf(“%d”, i);
if(i==5)
break;
}
getch();
Output:
12345
Continue statement
The continue statement skips the current iteration of the loop and continues with the next iteration. The
continue statement is used inside the body of loop statement. it is used when we want to go to the next
iteration of the loop after skipping the some of the statement of loop.
The difference between break and continue is that when a break statement is encountered the loop
terminates and the control is transferred to the next statement following the loop, but when a continue
statement is encountered the loop is not terminated and the control is transferred to the beginning of the
loop.
}
output:
1
2
3
4
6
7
8
8
10
out of for loop
goto statement
Goto statement in C is a jump statement that is used to jump from one part of the code to any other part of
the code in C. Goto statement helps in altering the normal flow of the program according to our needs. This
is achieved by using labels, which means defining a block of code with a name, so that we can use the goto
statement to jump to that label.
Syntax:
label_name:
.statement1;
.statement2;
.
.statementn;
goto label_name;
Function
A function is a block of code that performs a specific task when it is called.
The function is also known as procedureor subroutine in other programming languages. Function enable us
to write code separately for different functions.
Syntax:
return_type function_name( parameter list )
{
body of the function
}
Types of function
There are two types of function in C programming:
User Defined functions: Those functions that are created by user as per his/her need. Such Functions are
known as User Defined functions.
BASIS FOR
ACTUAL PARAMETER FORMAL PARAMETER
COMPARISON
They are actual values passed to a They are the variables in the function
Definition function on which the function will definition that would receive the values
perform operations when the function is invoked
Data types are not mentioned with the Data types are mentioned along the formal
Data types
actual parameters parameters
#include<stdio.h>
void greater();
void greater()
{
int a,b;
printf(“enter two numbers:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“%d is greater”, a);
}
else
{
printf(“%d is greater”, b);
}
}
int main(){
greater();
return 0;
#include<stdio.h>
int greater();
int greater( int a, int b)
{
if(a>b)
return a;
else
return b;
}
int main()
{
int a,b,c;
printf(“enter a and b:”);
scanf(“%d%d”,&a,&b);
c=greater(a,b); //
printf(“greater is %d”,c);
return 0;
}
#include<stdio.h>
void greater(int x, int y);
#include<stdio.h>
int greaternumber();
int greaternumber(){
int a,b;
printf(“enter two numbers:\n”);
scanf(“%d%d”,&a,&b);
if(a>b)
return a;
else
return b;
}
int main()
{
int greater;
greater=greaternumber();
printf(“%d is greater”,greater);
return 0;
}
TO perferm sum
#include<stdio.h>
void sum();
void sum()
{
int a,b, c;
printf(“enter two numbers:”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum is %d”, c);
int main(){
sum();
return 0;
To Perform sum
#include<stdio.h>
int sum(int int);
int sum(int x, int y)
{
int z=x+y;
return z;
}
int main()
{
int a,b,s;
printf(“enter two number\n:”);
scanf(“%d%d”, &a, &b);
s=sum(a,b);
To Perform Sum
//Example of Function with argument without return
#include<stdio.h>
void sum(int int);
void sum(int x, int y)
{
int s;
s=x+y;
printf(“sum is %d”,s);
}
int main()
{
int a,b,s;
printf(“enter two number\n:”);
scanf(“%d%d”, &a, &b);
s=sum(a,b);
return o;
}
To perform sum
#include<stdio.h>
int sum();
int sum(){
int x,y, s;
printf(“enter two numbers:\n”);
scanf(“%d%d”,&a,&b);
s=x+y;
return s;
}
int main()
{
int a;
a=sum();
printf(“%d is sum”,a);
return 0;
There are two methods to pass the data into the function in C language, i.e., call by value and call by
reference.
HOW TO CALL C FUNCTIONS IN A PROGRAM?
1. Call by value
2. Call by reference
1. CALL BY VALUE:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(” values before swap m = %d \nand n = %d”, m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(” \nvalues after swap m = %d\n and n = %d”, a, b);
}
2. CALL BY REFERENCE:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf(“values before swap m = %d \n and n = %d”,m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf(“\n values after swap a = %d \nand b = %d”, *a, *b);
}
Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
2
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.
Actual and formal arguments are created at the Actual and formal arguments are created at the
3
different memory location same memory location
Recursion
Function that call itself is called recursion. While using recursion, programmers need to be careful to define
an exit condition from the function, otherwise it will go into an infinte loop.
Syntax:
void recursion() {
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
#include <stdio.h>
int fibonacci(int); // function declaration
if(x == 0) {
return 0;
}
if(x == 1) {
return 1;
}
else
return fibonacci(x-1) + fibonacci(x-2); //function call itself
}
Array:
An array is a collection of values of similar kinds of data types. Values in array accessed using array name
with subscripts in brackets[]. Syntax of array declaration is:
data_type array_name[size];
#include<stdio.h>
int main()
{
int i,a[10]={10,20,39,58,19};
for(i=0;i<10;i++)
{
printf(“%d\n”,a[i]);
}
return 0;
}
Output:
10
20
39
58
19
0
0
0
0
0
Declaration and initialization of array
An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can
create an array for it.
dataTypearrayName[arraySize];
int data[100];
Accessing array
Array can be accessed using array-name and subscript variable written inside pair of square brackets [].
for example:
arr[3] = Third Element of Array
arr[5] = Fifth Element of Array
arr[8] = Eighth Element of Array
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main()
{
int i, array[5];
printf(“Enter 5 integers: “);
// taking input and storing it in an array
for(i = 0; i < 5; i++)
{
scanf(“%d”, &array[i]);
}
printf(“printing those values: “);
// printing elements of an array
for( i = 0; i < 5; ++i)
{
printf(“%d\n”, array[i]);
}
return 0;
}
data_type array_name[][][]…;
A pointer is a variable that stores the memory address of another variable as its value. Pointer variable is
always preceded by * operator.
if a pointer variable p is declared as : int *p;
it signifies p is pointer variable and it can store address of integer variable (i.e. it can not store address of
other type’s variables.
* operator is deference operator
& operator is reference operator
An indirection operator, is an operator used to obtain the value of a variable to which a pointer points. While
a pointer pointing to a variable provides an indirect access to the value of the variable stored in its memory
address, the indirection operator dereferences the pointer and returns the value of the variable at that
memory location. The indirection operator is a unary operator represented by the symbol (*). The indirection
operator is also known as the dereference operator.
Valid Examples:
int *p;
int num;
p=#
Invalid Examples:
int *p;
float num;
p=# /* invalid pointer variable p cannot store address of float variable */
Pointer Declaration
A pointer variable is declared as follows:
Syntax:
data_type * variable_name;
here, *is called indirection or dereference operator and variable_name is now pointer.
Example:
int *x;
float *y;
char *rajesh;
return 0;
}
Output:
50 is value of a variable
50 is the value of pointer
000000000062FE14 is the memory address of pointer variable
000000000062FE14 is the address of pointer
STRINGS:
An array of characters are known as Strings. There are various built-in string handling functions in c. Some
of them are:
1. strcpy()
2. strcat()
3. strcmp()
4. strcmpi()
5. strupr()
6. strlwr()
7. strrev()
Structure:
The structure is the collection of different data types grouped under the same name using the struct
keyword. It is also known as the user-defined data type that enables the programmer to store different data
type records in the Structure. Furthermore, the collection of data elements inside the Structure is termed as
the member.
File Hanndling in C
A file represents a sequence of bytes on the disk where a group of related data is stored. Various operations
can be done such as creating a file, opening a file, reading, writing, moving to a specific location in a file, and
closing a file.
File handling in C enables us to create, update, read, and delete the files stored on the local file system
through our C program. Some operations can be performed on a file.
Creation of the new file
Opening an existing file
Reading from the file
Writing to the file
Deleting the file
Useful Links
Home
Services
Contact Me
Terms & Conditions
Worked with
BidhyaTech
JK Arts
MastaSoftsolution
Ghodaghodi Multiple Campus
Location
Ghodaghodi Municipality-1, Kailali Nepal