0 ratings 0% found this document useful (0 votes) 13 views 44 pages C Complete Notes-1
C is a general-purpose, structured programming language developed in 1972 by Dennis Ritchie, known for its simplicity and flexibility, and is considered the mother language of modern programming languages. It is widely used for system software and applications, providing core concepts like arrays, strings, and functions, and features such as dynamic memory management and pointers. The document also covers basic commands, tokens, and operators in C, highlighting its machine independence and efficiency.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save C Complete Notes-1 For Later Chap 1
Introduction To C
What Is C Language
Cis a general-purpose programming language that is extremely popular, simple, and
flexible to use. It is a structured programming language that is machine-independent and
extensively used to write various applications, Operating Systems like Windows, and many
other complex programs like Oracle database, Git, Python interpreter, and more.
All the C programs are writen into text files with extension ".c" for example hello.c.
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, CH, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that
are being used in many languages like C++, Java, C#t, etc.
It can be defined by the following ways:
Mother language
System programming language
Procedure-oriented programming language
Structured programming language
ye ene
Mid-level programming language
1) Casa 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,
CH, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are
being used in many languages like C++, Java, Ci, etc.
2) Casa system programming language : A system programming language is used to create
system software. 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.
It can't be used for internet programming like Java, .Net, PHP, etc.
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.
© scone wine scarA procedural language breaks the program into functions, data structures, etc.
Cis a procedural language. In C, variables and function prototypes must be declared before
being used.
4) Casa 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).
ALow-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.
© 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.
It 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.
languages that were developed before C language.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
c99 1999 Standardization Committee
© scone wine scar© Features Of C
1. Simple 6. Memory Management
2. Machine Independent or Portable 7. Fast Speed
3. Mid-level programming language 8. Pointers
4. structured programming language 9. Recursion
5. Rich Library 10.Extensible
1) Simple : Cis a simple language in the sense that it provides a structured approach (to
break the problem into parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable : Unlike assembly language, c programs can be
executed on different machines with some machine specific changes. Therefore, C is a
machine independent language.
3) Mid-level programming language : Although, C isintended to do low-level
programming. It is used to develop system applications such as kernel, driver, etc. It also
supports the features of a high-level language. That is why it is known as mid-level
language.
4) Structured programming language : C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify. Functions also provide code reusability.
5) Rich Library : C provides a lot of inbuilt functions that make the development fast.
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) Speed : The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead.
8) Pointer : C provides the feature of pointers. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion : In C, we can call the function within the function. It provides code reusability
for every function. Recursion enables us to use the approach of backtracking.
10) Extensible : C language is extensible because it can easily adopt new features.
Basic Commands Of C
© scone wine scarC Basic commands Explanation
#include This command includes standard input output header file(stdio.h)
from the C library before compiling a C program
int main() Itis the main function from where C program execution begins.
{ Indicates the beginning of the main function.
/*_some_comments_*/| Whatever written inside this command “/* */” inside aC program,
it will not be considered for compilation and execution.
printf(“Hello_World! “); | This command prints the output on the screen.
getch(); This command is used for any character input from keyboard.
return 0; This command is used to terminate a C program (main function)
and it returns 0.
} It is used to indicate the end of the main function.
‘* How C Programming Language Works?
C is a compiled language. A compiler is a special tool that compiles the program and
converts it into the object file which is machine readable. After the compilation process, the
linker will combine different object files and creates a single executable file to run the
program. The following diagram shows the execution of a ‘C’ program
writing @
source-code
Compiling a
source-code
Linking
object-files
Nowadays, various compilers are available online, and you can use any of those
compilers. The functionality will never differ and most of the compilers will provide the
features required to execute both ‘C’ and ‘C++’ programs.
© Tokens in C
Tokens in Cis 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 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:
© scone wine scarn
3
oe tr
ey Special
Eran
Classification of C Tokens
1. Keywords in C
2. Identifiers in C
3. Strings in C
4. Operators in C
s. Constant in C
6. Special Characters in C
7. Variables
a. Data Types
1. Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-defined
words used by the compiler, so they cannot be used as the variable names. If the keywords
are used as the variable names, it means that we are assigning a different meaning to the
keyword, which is not allowed. C language supports 32 keywords given below:
auto double int struct
break | else long switch
case enum register typedef.
char extern return union
const__| float short unsigned
continue_| for signed void
default__| goto sizeof volatile
do if static while
2. Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers
in Care 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:
(© scanned wt onENScnner© 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.
© Itshould not begin with any numerical digit.
* In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
Commas or blank spaces cannot be specified within an identifier.
Keywords cannot be represented as an identifier.
The length of the identifiers should not be more than 31 characters.
Identifiers should be written in such a way that it is meaningful, short, and easy to read.
ee ee
3. 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 af] vatpoint"; // The compiler allocates the memory at the run time.
char a[10] = {ij,'a','V,'a',t!/p''0',i''n''t,\0'}; // String is represented in the form of
characters.
4, Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which
the operators are applied are known as operands. Operators are applied between the
operands. Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the list
of the binary operators:
o Arithmetic Operators
© Relational Operators
Logical Operators
© scone wine scar© Assignment Operator
© Conditional Operators
© Bitwise Operators
1. Arithmetic Operators :
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)
Example
#include
#include
void main()
{
inta=9,b=4,c;
c= ath;
printf("a+b = %d \n",c);
c=ab;
printf("a-b = %d \n",c);
c=a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
a%b;
(© scanned wt onENScnnerprintf("Remainder when a divided by b = %d \n",c);
getch();
2. Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Operator | Meaning of Operator Example
= Equal to 5 ==3 is evaluated to0
> Greater than 5 >3 is evaluated to 1
< Less than 5 <3 is evaluated to 0
I= Not equal to 5 |=3 is evaluated to 1
= Greater than or equal to 5 >=3 is evaluated to 1
<= Less than or equal to is evaluated to 0
Example
#include
#include
void main()
{
inta=5,b=5,c=10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printi("%d > %d is %d \n", a, b, a> b);
printi("%d > %d is 96d \n", a, c, a> c);
printi("%d < %d is %d \n", a, b, a= %d is 9d \n", a, b, a >= b);
printf("6d >= 9d is %d \n", a, c, a >= c);
printf("g6d <= %d is %d \n", a, b, a <=b);
printf("6d <= 9d is %d \n", a, c, a <= c);
getch();
3. Logical Operators :
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are commonly used in decision making in C
programming.
Operator | Meaning Example
BR Logical AND. True only if all 5 and d=2 then, expression
operands are true 3) && (d>5)) equals to 0.
II Logical OR. True only if either 5 and d = 2 then, expression
one operand is true ) 11 (d>5)) equals to 1.
! Logical NOT. True only ifthe | If c= 5 then, expression !(c==5) equals
operand is 0 to0.
Example
#include
#include
void main()
{
inta=5,b=5,c=10, result;
© scone wth one carresult = (a == b) && (c > b);
printf("(a
b) && (c > b) is %d \n", result);
result = (a == b) && (c< b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (¢
include
void main()
{
inta=5,¢;
cza; //cisS
printf("c = %d\n", c);
ctsa; //cis10
printf("c = %d\n", c);
c
3 Mciss
printf("c = %d\n", c);
// cis 25
printf("c = 96d\n", c);
cl=a; //cisS
printf("c = %d\n", c);
c%=a; //c=0
printi("c = %d\n", c);
© scone wih one camegetch();
5. Constants in C
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
There are two ways of declaring constant:
Using const keyword
© Using #idefine pre-processor
‘Types of constants in C
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point 45.6, 67.8, 11.2, etc.
constant
Octal constant 011, 088, 022, etc.
Hexadecimal constant _| Oxla, Ox4b, Oxéb, etc.
Character constant ‘a’, 'b', 'c', etc.
String constant "java", "c++", "net", etc.
6. Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets (): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
© Curly braces { }: It is used in the opening and closing of the code. It is used in the
‘opening and closing of the loops.
© 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.
© Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
© scone wine scar© Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
© Tilde (~): Itis used as a destructor to free memory.
© Period (,): Itis used to access a member of a structure or a union.
7. Variables
The variables in C language are used to store data of different types such as integer, float,
character, etc. There are many types of variables depending on the scope, storage class,
lifetime, type of data they store, etc. They are the basic building block of a C program.
What is a variable in C?
A variable in Cis a memory location with some name that helps store some form of
data and retrieves it when required. We can store different types of data in the variable and
reuse the same variable for storing some other data any number of times.
C Variable Syntax
data_type variable_name = value; // defining single variable
or
data_type variable_namel, variable_name2; // defining multiple variable
Variable Declaration in C
Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type. No memory is allocated to a variable in the declaration.
You can assign any name to the variable as long as it follows the following rules:
A variable name must only contain alphabets, digits, and underscore.
A variable name must start with an alphabet or an underscore only. It cannot start with a
digit.
No whitespace is allowed within the variable name.
A variable name must not be any reserved word or keyword.
8. Data Types
© scone wine scarDatatypes in C
Data Types [Memory Size | Range Format Specifier
char 1byte 128 to 127 ec
int 2 byte =32,768 to 32,767 %d.
float A byte -3.4E* to 3.46" oF
double 8 byte 71.78 to 1.76% MIF
Long Abyte -2,147,483,648 to | %Id
2,147,483,647
1. Integer Types
The integer data type in C is used to store the whole numbers without decimal values.
+ Range: -2,147,483,648 to 2,147,483,647
+ Size: 2 bytes or 4 bytes
+ Format Specifier: %d
C program to print Integer data types.
#include
int main()
{
inta=9;
intb=
int ¢ = 89U;
long int d = 999981;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);
(© scanned wt onENScnnergetch();
getch();;
2. Character Types
Character data type allows its variable to store only a single character. The storage size of
the character is 1. It is the most basic data type in C.
+ Range: (-128 to 127) or (0 to 255)
+ Size: 1 byte
+ Format Specifier: %c
// C program to print Integer data types.
#include
int main()
{
char a=
char c;
printf("Value of a: %c\n", a);
att;
printf("Value of a after increment is: 9c\n", a);
= 99;
printf("Value of ¢: 9c", c);
gectch();
getch();;
3. Float
In C programming float data type is used to store floating-point values. Float in C is used
to store decimal and exponential values.
+ Range: 1.2E-38 to 3.4£+38
+ Size: 4 bytes
+ Format Specifier: %f
© scone wine scar// of Floating types
#include
int main()
{
float a = 9.0f;
float b = 2.5f;
float c = 2E-4f;
printf("9f\n",
printf("96F\n",b);
printf("%F",¢);
getch();;
}
4. Double
A Double data type in Cis used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.
+ Range: 1.7E-308 to 1.7E+308
+ Size: 8 bytes
« Format Specifier: %lf
// use of double data type
#include
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("9lf\n", a);
printf("%lIf\n", b);
printf("%If", c);
getch();;
© scanned wt oHEN SconesC Programs :
5. Name program
// our own name using printf)
#include
ain
int main()
{
// print name
printf("Name : GeeksforGeeks");
getch();;
getch();
}
// our own name using scanf()
Hinclude
#include
void main()
{
char name[20];
printf("Enter name: ");
// user input will be taken here
scanf("%s", name);
printf("Your name is %s.", name);
getch();;
getch();
6. IntegerValue
© scanned wt oHEN Scones//\nteger value
#include
#include
void main()
{
// Declaring integer
intx=5;
// Printing values
printf("Printing Integer value %d", x);
getch();
getch();;
}
// as input and print it
#include
fin
void main()
{
// Declare the variables
int num;
// Input the integer
printf("Enter the integer: ");
scanf("%d", &num);
// Display the integer
printf("Entered integer is: %d", num);
getch();
getch();;
© scanned wt oHEN Scones7. C Program to Add Two Integers
//C program to add two numbers
Hinclude
#include
void main()
{
int A, B, sum = 0;
// Ask user to enter the two numbers
printf("Enter two numbers A and B : \n");
// Read two numbers from the user
scanf("%d%d", &A, &B);
// Calculate the addition of A and B
//using '+' operator
sum = A+B;
// Print the sum
printf("Sum of A and Bis: 9d", sum);
getch();;
8. C Program to Multiply two Floating Point Numbers
//C program to multiply two floating point numbers
include
#include
void main()
{
float A, B, product = 0.0f;
// Ask user to enter the two numbers
printf("Enter two floating numbers A and B : \n");
// Read two numbers from the user || A = 2.12, B= 3.88
scanf("%f9%F", &A, &B);
© scone wth one car// Calculate the multiplication of A and B
/Lusing *' operator
product = A * B;
// Print the product
printf("Product of A and B is: %f", product);
getch();;
9. c program for calculate marks and total
/*C program to calculate total, average and percentage of five subjects*/
#include
#include
void main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;
/* Input marks of all five subjects */
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%F", &eng, &phy, &chem, &math, &comp);
/* Calculate total, average and percentage */
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
/* Print all results */
printf("Total marks = %.2f\n", total);
printf(" Average marks = %.2f\n", average);
printf(" Percentage = %.2f", percentage);
getch();;
© scanned wt oHEN Scones10.C Program To Find Area And Perimeter of Rectangle
//C program to demonstrate the
// area and perimeter of rectangle
#include
#include
void main()
{
int |= 10, b = 10;
int A, P;
A=I*b;
P=2*(I+b);
printf("Area of rectangle is : %d", A);
printf("\nPerimeter of rectangle is : 9d”
getch();
11. Program to Find Area of Circle
#include
#include
void main() {
float pie = 3.14;
int radius;
printf("Enter The Radius of Cicle:");
scanf("%d", &radius);
printf("The radius of the circle is %d\n" , radius);
float area = (float)(pie* radius * radius);
printf("The area of the given circle is %f", area);
getch();
© scone wth one car12.Program to find area of a triangle
/*C program to find area of a triangle if base and height are given */
#include
#include
void main()
{
float base, height, area;
/* Input base and height of triangle */
printf("Enter base of the triangle: ");
seanf("%f", &base);
printf("Enter height of the triangle:
scanf("%f", &height);
/* Calculate area of triangle */
area = (base * height) / 2;
/* Print the resultant area */
printf(""Area of the triangle = %.2f sq. units", area);
getch();}
Flowcharts:
Flowchart is a graphical representation of an algorithm. Programmers often use it as a
program-planning tool to solve a problem. It makes use of symbols which are connected
among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”’.
Basic Symbols used in Flowchart Designs
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A
pause/halt is generally used in a program logic under some error conditions.
Terminal is the first and last symbols in the flowchart.
© scone wine scar2. Input/Output: A parallelogram denotes any function of input/output type. Program
instructions that take input from input devices and display output on output devices
are indicated with parallelogram in a flowchart.
3. Processing: A box represents arithmetic instructions. All arithmetic processes such
as adding, subtracting, multiplication and division are indicated by action or process
symbol.
4. Decision Diamond symbol represents a decision point. Decision based operations
such as yes/no question or true/false are indicated by diamond in flowchart.
>
5. Connectors: Whenever flowchart becomes complex or it spreads over more than
one page, it is useful to use connectors to avoid any confusions. It is represented by
acircle.
6. Flow lines: It represents the exact sequence in which instructions are executed.
Arrows are used to represent the flow lines in a flowchart. The symbol given below is
used for representing the flow lines:
(© scanned wt onENScnner2 Chap
Control Structure
In simple words, Control statements in C help the computer execute a certain logical
statement and decide whether to enable the control of the flow through a certain set of
statements or not. Also, it is used to direct the execution of statements under certain
conditions.
Simple if statement
If-else statements
Nested if-else statements
else-if ladder
Switch Statement
1. Simple if Statement
Simple if statements are carried out to perform some operation when the condition is only
true. If the condition of the if statement is true then the statements under the if block is
executed else the control is transferred to the statements outside the if block.
Syntax :
If(Condition) Flow Chart :
if (sae)
Statement ;
Example:
#include
(© scanned wt onENScnner#include
void main()
{
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if{number%2==0)
{
printf("Number Is Even”);
}
getch();
2. If-else Statement
In some situations, you may have to execute statements based on true or false under
certain conditions, therefore; you use if-else statements. If the condition is true, then if
block will be executed otherwise the else block is executed.
Syntax :
If(Condition) Flow Chart :
{
(«mn >)
Statement; ——
} < expression >-false-
else ;
tne
{ 4
statomentsin | _[ statementsin
Statement; if branch else branch
}
stop je]
Example:
#include
#includesconio.h>
void main()
{
int number=0;
printf("enter a number:
(© scanned wt onENScnnerscanf("%d", &number);
if{number%2==0)
{
printf("d is even number" number);
}
else
{
printf("%d is odd number" number);
}
getch();
3. Else-if Ladder Statements
The else-if ladder statements contain multiple else-if, when either of the condition is true
the statements under that particular “if” will be executed otherwise the statements under
the else block will be executed.
Suppose the “if” condition is true, statements under “if” will be executed else the other “if”
condition is tested, and if that condition is true statements under that particular “if” will be
executed. This process will repeat as long as the else-if’s are present in the program.
Syntax: Flow Chart :
If(Condition)
Statement;
}
else if(Condition) Canta
| 1
:
Statement; =
}
eo
else if(Condition)
{
(© scanned wt onENScnnerStatement;
}
else if(Condition)
{
Statement;
}
else
{
Statement;
}
Example :
#include
#include
void main (){
int a,b,c,d;
printf("Enter the values of a,b,c,d: \n");
scanf"%d%d%d%d", Ba, &b,&c, &d);
ifla>b && a>c && a>d){
printf("géd is the largest",a);
}
else if(b>c && b>a && b>d){
printf("g%d is the largest",b);
}
else if(c>d && c>a && c>b){
© scanned wt oHEN Sconesprintf("géd is the largest",);
}
else{
printf("s%6d is the largest",d);
}
getch();
4. Nested if else statement in C
One of the fundamental constructs in programming is conditional statements. They allow a
program to take different paths based on the values of certain conditions. In C, conditional
statements are implemented using if-else statements. In more complex scenarios, nested if-
else statements can be used to make more sophisticated decisions. This blog post will provide
an in-depth explanation of nested if-else statements in C, including syntax, example, and
output.
Syntax: Flow Chart :
if (condition)
{
if (condition2)
{
Statement ;
}
else
{
Statement
) —__| J
else [Samer jt
‘elu
{
Tess Nee ke
er
Statement ;
) &
Example :
#include
(© scanned wt onENScnner#include
void main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number?) {
if (number == number?) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
getch();
5. switch Statement
In the C program, the switch statement is used when you have multiple possibilities for
the if statement. The switch case allows you to choose from several options. For example,
when we compare it with a regular electric switchboard, you will have many switches in the
switchboard, but you will select only the required buttons; similarly, the switch case allows
you to set the necessary statements for the user.
syntax : Flow Chart :
switch (expression)
{
case constant
// statements
break;
© scone wine scarcase constant2: [commana bar
// statements on TT
break; tal
default:
// default statements
Example :
#include
#include
Void main()
{
int week;
printf("Enter week number(1-7):
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
(© scanned wt onENScnnerbreak;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6.
printf("Saturday");
break;
case 7.
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
getch();
C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of the
tutorial, we are going to learn all the aspects of C loops.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
There are three types of loops in C language that is given below:
© scone wine scar1. do while
2. while
3. for
1. for Loop
for loop in C programming is a repetition control structure that allows programmers to
write a loop that will be executed a specific number of times. for loop enables
programmers to perform n number of steps together in a single line.
Syntax:
for (initialization; Condition;
Increment/Decrement)
{
Statements;
} rae
Example:
iiinclude
#include
void main()
{
int i=0;
for (i=
{
; <= 10; i++)
printf{ "Disha Computers\n");
}
getch();
}
Flowcharts :
© scanned wth onEN Scanner2. While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is terminated
on the basis of the test condition. If the test condition will become false then it will break
from the while loop else body will be executed.
Syntax:
initialization; CH)
while (Condition)
{ <> =.
Statement;
Increment/Decrement;
Example:
#include
#include
void main()
{
inti=4;
while(i <= 10)
{
printf( "%6dDisha Computers\n"
it;
}
getch();
}
3. 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.
(© scanned wt onENScnnerSyntax:
initialization;
do
{
Statement;
Increment/Decrement;
} while (Condition); Km!
Example:
iiinclude
include
void main()
printf( "sed\tDisha Computers\n",i);
it;
} while (i <=5);
getch();
}
© scanned wth onEN ScannerChap 3
C Arrays
Array in Cis one of the most used data structures in C programming. It is a simple and fast
way of storing multiple values under a single name. In this article, we will study the
different aspects of array in C language such as array declaration, definition, initialization,
types of arrays, array syntax, advantages and disadvantages, and many more.
Definition:
An array in Cis a fixed-size collection of similar data items stored in contiguous memory
locations. It can be used to store the collection of primitive data types such as int, char,
float, etc., and also derived and user-defined data types such as pointers, structures, etc.
iz
[ehehi
Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare
an array by specifying its name, the type of its elements, and the size of its dimensions.
When we declare an array in C, the compiler allocates the memory block of the specified
size to the array name.
Syntax :
data_type array_name [size];
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as
follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1, One Dimensional Array
The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only
one dimension.
Syntax of 1D Array in C
array_name [size];
1D Array
1[2/3]4[5|6/7/8)
© scone wine scarExample:
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some
of the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare
arrays with more dimensions than 3d arrays but they are avoided as they get very
complex and occupy a large amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in Cis an array that has exactly two dimensions.
They can be visualized in the form of rows and columns organized in a two-dimensional
plane.
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D
Array. A 3D array has exactly three dimensions. It can be visualized as a collection of 2D
arrays stacked on top of each other to create the third dimension.
(© scanned wt onENScnnerChap 4
String
A String in C programming is a sequence of characters terminated with a null character
‘\0’. The C String is stored as an array of characters. The difference between a character
array and a C string is the string is terminated with a unique character ‘\0’.
C String Declaration Syntax :
Declaring a string in Cis as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_namelsize];
In the above syntax str_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
There is an extra terminating character which is the Null character ('\0’) used to indicate
the termination of a string that differs strings from normal character arrays.
C STRING FUNCTIONS
There are many important string functions defined in "string.h" library.
No. | Function Description
1) | strlen(string name! returns the length of string name.
2) | strcpy(destination, copies the contents of source string to
source) destination string.
3) | streat(first_string concats or joins first string with second string.
second _string} The result of the string is stored in first string.
4) | stremp(first_string, ‘compares the first string with second string. If
second string) both strings are same, it returns 0.
5) _| strrev(string) returns reverse string.
6) _| strlwr(string) returns string characters in lowercase.
7)_| strupr(string) returns string characters in uppercase.
© scone wih one cameChap 5
Function
A function in C is a set of statements that when called perform some specific task. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain
meanings and performing certain operations. They are also called subroutines or
procedures in other languages.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3, Function Calls
Function Declarations
Ina function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that there is
a function with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
1
int sum (int a, int b );
Ti) Let
Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly. The below example serves as both a function definition and a declaration.
© scone wine scarFunction Definition
HEADER [Int heading (oi)
statements
return 0,
)
Function Call
A function call is a statement that instructs the compiler to execute the function. We use
the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned
back to the main function of the program.
Working of Function in
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
Types of Functions
——_,
User Defined Library
Function Function
Library Function
A library function is also referred to as a “built-in function”. A compiler package already
exists that contains these functions, each of which has a specific meaning and is included in
the package. Built-in functions have the advantage of being directly usable without being
defined, whereas user-defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), stremp(), strcpy() etc.
User Defined Function
(© scanned wt onENScnnerFunctions that the programmer creates are known as User-Defined functions or “tailor-
made functions”. User-defined functions can be improved and modified according to the
need of the programmer. Whenever we write a function that is case-specific and is not
defined in any header file, we need to declare and define our own functions according to
the syntax.
In C programming language, functions can be called either with or without arguments and
might return values. They may or might not return values to the calling functions.
1. Function with no arguments and no return value
2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value
(© scanned wt onENScnnerCHAP 6
C STRUCTURES
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype, We can use the struct keyword to declare
the structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
b
The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
Wariable1, varaible2, ...;
2. Structure Variable Declaration after Structure Template
// structure declared beforehand
struct structure_name variable1, variable2,
1. Structure Using Array
2. Nested Structure
3. Sizeof Structure
(© scanned wt onENScnnerCHAP 7
C UNIONS
The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure. But unlike structures, all the members in the C
union are stored in the same memory location. Due to this, only one member can store
data at the given instance.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’
names and data types along with the name of the union. No memory is allocated to the
union in the declaration.
union union_name {
datatype member1;
datatype member2;
, a
Keep in mind that we have to always end the union declaration with a semi-colon.
Different Ways to Define a Union Variable
We need to define a variable of the union type to start using union members. There are
two methods using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
} vari, var2, ...)
2. Defining Union Variable after Declaration
union union_name var, var2, var3..
where union_name is the name of an already declared union.
(© scanned wt onENScnnerCHAP 8
C POINTERS
Pointers are one of the core components of the C programming language. A pointer can be
used to store the memory address of other variables, functions, or even other pointers.
The use of pointers allows low-level memory access, dynamic memory allocation, and
many other functionality in C.
Syntax
The syntax of pointers is similar to the variable declaration in C, but we use the ( *)
dereferencing operator in the pointer declaration.
datatype * ptr;
where
+ ptr is the name of the pointer.
+ datatype is the type of data it is pointing to.
(© scanned wt onENScnnerCHAP 8
FILE HANDLING
File handing in C is the process in which we create, open, read, write, and close operations
ona file.
To perform input, output, and many different C file operations in our program.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in
Csuch as:
1. Creating a new file — fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file - fopen()
3. Reading from file — fscanf() or fgets()
4. Writing to a file fprintf() or fputs()
5. Moving to a specific location in a file ~ fseek(), rewind()
6. Closing a file - fclose()
No. [Function | Description
1__[fopen() | opens new or existing file
2__|fprintf() _| write data into the file
3 _|fscanf()__| reads data from the file
4 |fputc() _| writes a character into the file
5__|fgetc() _| reads a character from file
6 | fclose() _| closes the file
7__|fseek() _| sets the file pointer to given position
8 | fputw() _ | writes an integer to file
9 |fgetw() | reads an integer from file
10_| ftell() returns current position
11_[rewind() [sets the file pointer to the beginning of the file
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use
the FILE macro to declare the file pointer variable. The FILE macro is defined
inside header file.
Syntax of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
© scone wth one car