c lagng-converted (12)
c lagng-converted (12)
Procedural Language:
In procedural languages, the program code is written as a sequence of
instructions. User has to specify “what to do” and also “how to do” (step by
step procedure). These instructions are executed in the sequential order.
These instructions are written to solve specific problems.
Applications of C Programming
C was initially used for system development work, particularly the programs
that make-up the operating system. C was adopted as a system development
language because it produces code that runs nearly as fast as the code
written in assembly language. Some examples of the use of C are -
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Structure of c program
Hello World
#include <stdio.h>
main()
{
/* my first program in C */
printf("Hello, World! \n");
C 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. For example:
int a;
Do if static while
C Identifiers
Identifiers are names given to different entities such as constants, variables, structures, functions,
etc.
int money;
Also remember, identifier names must be different from keywords. You cannot use int as an
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
4. There is no rule on how long an identifier can be. However, you may run into problems in some
type variable_name;
or
type variable_name, variable_name, variable_name;
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like
addition (+), subtraction (-), multiplication (*), division (/) and modulus
(%).These are binary operators(apply more than one operands)
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Operator Description
++ Increment
−− Decrement
void main()
{
//set a and b both equal to 5.
int a=5, b=5;
//Print them and decrementing each time.
//Use postfix mode for a and prefix mode for b.
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
}
Program Output:
5 4
4 3
3 2
2 1
1 0
Relational Operators
Relational operators are used to comparing two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
int main()
{
int m=40,n=20;
if (m = = n)
printf("m and n are equal");
else
printf("m and n are not equal");
or
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m != n)
printf("m and n are no equal");
else
printf("m and n are equal");
Logical Operators
C provides three logical operators when we test more than one condition to
make decisions. These are: && (meaning logical AND), || (meaning logical
OR) and ! (meaning logical NOT).
Operator Description
&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates
to False, the result is False)
|| Or operator. It performs a logical disjunction on two expressions. (if either
or both expressions evaluate to True, the result is True)
include <stdio.h>
int main()
{
int m=40, n=20;
int o=20, p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \
"But, status is inverted as false\n");
}
}
OUTPUT:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
Bitwise Operators
C provides a special operator for bit operation between two variables.
Operator Description
| Binary OR Operator
00001100
& 00011001
________
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output
Output = 8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
00001100
| 00011001
________
00011101 = 29 (In decimal)
Output = 29
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It
is denoted by ^.
00001100
^ 00011001
________
00010101 = 21 (In decimal)
Output
Output = 21
Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0
and 0 to 1. It is denoted by ~.
~ 00100011
________
11011100 = 220 (In decimal)
Assignment Operators
Assignment operators applied to assign the result of an expression to a
variable. C has a collection of shorthand assignment operators.
Operator Description
= Assign
Conditional Operator
C offers a ternary operator which is the conditional operator (?: in
combination) to construct conditional expressions.
Operator Description
?: Conditional Expression
#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;
}
Special Operators
C supports some special operators
Operator Description
* Pointer to a variable.
Control Statements
The control statements are used to control the cursor in a program according to the condition or
according to the requirement in a loop. There are mainly three types of control statements or
flow controls. These are illustrated as below:
• Branching
• Looping
• Jumping
Branching Statement
1. if statement
a. Simple if statement
b. if-else statement
c. nested if statement
d. else-if or ladder if or multi-condition if statement
2. switch statement
3. conditional operator statement
1. if statement
a. Simple if statement
The if statement is a powerful decision making statement which can handle a single condition
or group of statements. These have either true or false action....
When only one condition occurs in a statement, then simple if statement is used having one
block.
/*Any Number is input through the keyboard and check number is greater than 0.*/
void main()
int n;
n=1;
scanf("%d",&n);
if(n>0)
getch();
b. if-else statement
This statement also has a single condition with two different blocks. One is true block and
other is false block...
/*Any Number is input through the keyboard. write a program to find out whether It is and Odd
Number or Even Number.*/
Output is as :
Enter the Number
4
This is Even Number
c. nested if statement
When an if statement occurs within another if statement, then such type of is called nested if
statement. /*If the ages of Ram, sham and Ajay are input through the keyboard, write a program
to determine the youngest of the three*/
Output is as :
Enter the three Ages of Ram,Sham and Ajay
14
17
19
Ram is Youngest
When in a complex problem number of condition arise in a sequence, then we can use
Ladder-if or else if statement to solve the problem in a simple manner.
The marks obtained by a student in 5 different subjects are input through the keyboard. The student gets a
division as per the following rules:
Method 1
/*Write a program to calculate the division obtained by the student. There are two ways in
which we can write a program for this example. These methods are given below: */
//Method-1
#include< stdio.h >
#include< conio.h >
void main()
{
int eng,math,com,sci,ss,total;
float per;
clrscr();
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);
METHOD 2
//Method-2
#include< stdio.h >
#include< conio.h >
void main()
{
int eng,math,com,sci,ss,total;
float per;
clrscr();
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);
2. switch statement
When number of conditions (multiple conditions) occurs in a problem and it is very difficult
to solve such type of complex problem with the help of ladder if statement, then there is need of
such type of statement which should have different alternatives or different cases to solve the
problem in simple and easy way. For this purpose switch statement is used. .
/*WAP to print the four-days of week from monday to thrusday which works upon the choice as
S,M,T,H using switch case*/
scanf("%c",&n);
switch(n)
{
case 'S':
printf("Sunday");
break;
case 'M':
printf("Monday");
break;
case 'T':
printf("Tuesday");
break;
case 'H':
printf("Thursday");
break;
default:
printf("Out of Choice");
break;
}
getch();
}
Output is as :
Enter the Choice from Four Days...
S = Sunday
M = Monday
T = Tuesday
H = Thursday
S
Sunday
This statement is based on conditional operator. This statement solves the problem's condition
in a single line and is a fast executable operation. For this purpose we can take combination of ?
and :
//OR
getch();
}
Output is as :
Enter year 2020
Leap Year
Looping
1. for loop
2. while loop
3. do...while loop
1. For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop
syntax in C is as follows:
Output
1
2
3
4
5
6
7
8
9
10
// Print numbers from 10 to 1
#include <stdio.h>
main()
{
int i;
Output
10
9
8
7
6
5
4
3
2
1
While Loop in C
A while loop is the most straightforward looping structure. Syntax of while loop in C
programming language is as follows:
while (condition) {
statements;
}
Example 1: while loop
main()
{
int i=1;
Output
1
2
3
4
5
6
7
8
9
10
Do while Loop in C
A do while loop is similar to while loop with one exception that it executes the statements
inside the body of do-while before checking the condition. On the other hand in the for and
while loop, first the condition is checked and then the statements in for and while loop are
executed. So you can say that if a condition is false at the first place then the do while would
run once, however the while loop would not run at all. Note that do-while runs at least once
even if the condition is false because the condition is evaluated, after the execution of the
body of loop.
do
{
//Statements
}while(condition test);
#include <stdio.h>
main()
{
int j=1;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=10);
Output
1
2
3
4
5
6
7
8
9
10
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
main()
{
int num, count, sum = 0;
#include <stdio.h>
main()
{
int num, count = 1, sum = 0;
#include <stdio.h>
main()
{
int num, count = 1, sum = 0;
• Break
• Continue
• GoTo
Break Statement
Break
The break statement is used to terminate the loop or statement in which it present.
After that, the control will pass to the statements that present after the break
statement, if available. If the break statement present in the nested loop, then it
terminates only those loops which contains break statement.
#include<stdio.h>
void main()
{
int a=1;
while(a<=10)
{
if(a==5)
break;
printf("\nStatement %d.",a);
a++;
}
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statement 3.
Statement 4.
End of Program.
Continue Statement
Continue
This statement is used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop. Basically, it
skips its following statements and continues with the next iteration of the loop.
#include<stdio.h>
void main()
{
int a=0;
while(a<10)
{
a++;
if(a==5)
continue;
printf("\nStatement %d.",a);
}
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statemnet 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.
Goto Statement
goto
The goto statement is a jump statement which jumps from one point
to another point within a function.
goto label;
----------
----------
label:
----------
----------
#include<stdio.h>
void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");
goto last;
printf("\nStatement 4.");
printf("\nStatement 5.");
last:
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statement 3.
End of Program.
Scope rules
#include <stdio.h>
int main () {
/* actual initialization */
a = 10;
b = 20;
g = a + b;
Arrays in C
dataType arrayName[arraySize];
For example,
float mark[5];
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example 1: Array Input/Output
int main() {
int values[5];
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Here, we have used a for loop to take 5 inputs from the user
and store them in an array. Then, using another for loop,
these elements are displayed on the screen.
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
Two Dimensional or 2D Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays
are created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.
data_type array_name[rows][columns];
Int a[4][3];
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}};
Two-dimensional array example in C
#include<stdio.h>
int
main()
{
int i=0, j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf(" %d \t",arr[i][j]);
}//end of j
Printf(“\n”);
} //end of i
getch();
}
Output
1 2 3
2 3 4
3 4 5
4 5 6
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
/*
* C program to accept a matrix of order MxN and find its transpose
*/
#include <stdio.h>
void main()
{
static int array[10][10];
int i, j, m, n;
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for more than once in
a program. This may lead to unnecessary repetition of code, bugs and even becomes boring for
the programmer. So, C language provides an approach in which you can declare and define a
group of statements once in the form of a function and it can be called and used whenever
required.
These functions defined by the user are also know as User-defined Functions
C functions can be classified into two categories,
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at
the time of writing program. These functions are made for code reusability and for saving time
and space.
2. It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
3. In case of large programs with thousands of code lines, debugging and editing becomes
Function Declaration
General syntax for function declaration is,
Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its return
type. The actual body of the function can be defined separately. It's also called as Function
Prototyping. Function declaration consists of 4 parts.
• returntype
• function name
• parameter list
• terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected
to provide with some result at the end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function name is any
valid C identifier and therefore must follow the same naming rules like other variables in C
language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function
is called. They are often referred as formal parameters.
Type of User-defined Functions in C
There can be 4 different types of user-defined functions, they are:
#include<stdio.h>
main()
{
void sum(); // function declaration
sum(); // function call
}
#include<stdio.h>
main()
{
#include<stdio.h>
main()
{
int add;
int sum(); // function declaration
add = sum(); // function call
printf("The sum of number is: %d", add);
#include<stdio.h>
main()
{
int I,j;
void sum(int,int); // function declaration
printf("Enter 2 numbers ");
scanf("%d%d", &i, &j);
sum(i,j); // function call
#include<stdio.h>
main()
{
int add,I,j;
int sum(int, int); // function declaration
printf("Enter 2 numbers ");
scanf("%d%d", &i, &j);
add = sum(i,j); // function call
printf("The sum of number is: %d", add);
Pointers in C
Pointer is a variable in C that holds the address of another variable. They
have data type just like variables, for example an integer type pointer can hold
the address of an integer variable and an character type pointer can hold the
address of char variable.
Syntax of pointer
data_type *pointer_name;
Assignment
An integer type pointer can hold the address of another int variable. Here we
have an integer variable var and pointer p holds the address of var. To assign the
address of variable to pointer we use ampersand symbol (&).
p = &var;
#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
*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