0% found this document useful (0 votes)
12 views

Fundamentals of C

The document provides a comprehensive history of the C programming language, tracing its origins from ALGOL to its development by Dennis Ritchie in 1972. It discusses the standardization of C by ANSI and ISO to ensure compatibility and portability across systems, as well as its advantages, disadvantages, and applications in various fields. Additionally, it covers the features of C, including its data types, tokens, and the importance of identifiers and keywords in programming.

Uploaded by

ashishjha258146
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Fundamentals of C

The document provides a comprehensive history of the C programming language, tracing its origins from ALGOL to its development by Dennis Ritchie in 1972. It discusses the standardization of C by ANSI and ISO to ensure compatibility and portability across systems, as well as its advantages, disadvantages, and applications in various fields. Additionally, it covers the features of C, including its data types, tokens, and the importance of identifiers and keywords in programming.

Uploaded by

ashishjha258146
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 207

History of C Language

 The root of all modern languages is ALGOL (Algorithmic


Language). ALGOL was the first computer programming
language to use a block structure, and it was introduced
in 1960.

 In 1967, Martin Richards developed a language called


BCPL (Basic Combined Programming Language). BCPL was
derived from ALGOL.

 In 1970, Ken Thompson created a language using BCPL


called B. Both BCPL and B programming languages were
typeless.

 After that, C was developed using BCPL and B by Dennis


Ritchie at the Bell lab in 1972. So, in terms of history of
C language, it was used in mainly academic environments,
but at long last with the release of many C compilers for
commercial use and the increasing popularity of UNIX,
it began to gain extensive support among professionals.
History of C Language
 In 1969, Ken Thompson and Dennis Ritchie
designed a file system for Bell Laboratories in
order to provide a more convenient environment
for programming.

 This file system evolved into an early version of


the UNIX Operating System. Later, this file
system was implemented on a PDP-7 computer,
which was found lying idle, and in 1971, on PDP-
11.

 In an attempt to write a FORTRAN language


compiler for the new system, Thompson instead
developed the language B.
History of C Language
 B was interpreter-based, and thus had
performance drawbacks; so in 1972 Ritchie
developed the language C, which was compiler-
based.

 In 1973, the new file system was rewritten in C


language giving a thrust to its acceptance among an
increasing number of users.
History of C Language
Why Was C Language Standardized?

C was standardized by the American National


Standards Institute (ANSI) and International
Organization for Standardization (ISO) in
1983(ANSI)/1090(ISO).

The purpose behind it was to ensure the


compatibility and portability of C programs
across different computer systems and
hardware platforms.

The standardization process aimed to define a


common, standardized version of the language
that would be recognized and supported by all
manufacturers and users.
 Prior to standardization, there were several
different versions of C in use, each with slightly
different syntax and libraries, which made it
difficult for programs to be ported from one
system to another.

 The ANSI standardization of C provided a single,


widely accepted definition of the language, which
allowed programs to be written and compiled on
one platform and then run on other platforms
without modification.

 It had a major impact on the language, leading to


its widespread adoption and greater portability
of programs. Today, the ANSI standard remains
the most widely recognized definition of C, and
it is supported by most C compilers and libraries.
Why C Language ?
 C covers all the basic concepts of programming.
 It's good for learners to learn programming.

 It's a base or mother programming language to learn


object-oriented programming like C++, Java, .Net, etc.
Many modern programming languages, such as C++, Java,
and Python, have borrowed syntax and concepts from C.

 It provides fine-grained control over hardware, making it


highly efficient. As a result, C is commonly used to
develop system-level programs, like designing Operating
Systems, OS kernels, etc., and also used to develop
applications like Text Editors, Compilers, Network
Drivers, etc.

 C programs are portable; hence they can run on different


platforms without significant modifications.

 Still a significant demand for C programmers in various


industries.
Introduction to C
Low level programming languages are used for
system programming because they have
powerful features such as low-level access to
memory.

Similarly, high-level languages are used for


application programming because they are
flexible and easy to use.

C language combines the power of low-level


languages and the flexibility and simplicity of
high-level languages. Therefore, it is a widely
used computer language.
C as a Second and Third Generation
Language
C language possesses the powerful low-level
features of second generation languages such as
pointers, memory allocation, and bit-manipulation.
It also supports conditional constructs, loop
constructs, a rich list of operators, and a variety
of data structures as in third generation
languages.

The combined features of second and third


generation languages make C language a very
powerful and flexible language. These features of
C language make it possible to use the language for
systems programming, like development of
compilers, interpreters, operating systems,
graphics and general utilities, and also for a host
of applications in the commercial environment.
C language is so powerful and flexible that C
compilers are being written in earlier versions
of C language. C is also used to write other
applications, such as other language compilers,
databases, spreadsheets, and word processors.

Out of a total of 13,000 lines of code for the


Unix Operating System, all except 800 lines
have been written in C language.
Features of the C Language
C language has various features that
make it a widely-used language. Some of
the important features are:

Pointers
Memory Allocation
Recursion
Bit-manipulation
Features of the C Language
Pointers
C language, like other languages, allows reference
to a memory location by a name assigned to it. In
addition, C allows a user to refer to a memory
location (by its internal address or byte number)
by using pointers.

Memory Allocation
In almost all programming languages, memory is
assigned to a variable name at the time of
definition. C language also allows dynamic allocation
of memory, i.e. a program itself can request the
operating system to release memory for the use of
the program at the time of execution.
Features of the C Language
Recursion
A function may call itself. This feature, called
recursion, is supported by C language.

Bit-Manipulation
Unlike other languages, C allows manipulation
of data in its lowest form of storage - BITS.

For example, consider multiplication of a


number, m by 2. A familiar method to do so is
to compute (m * 2). Another method is to
shift the BITS of memory location m to the
left by one position, as shown in the following
table.
Features of the C Language
Value in m BIT representation BIT representation Value after BIT shift
of value in memory of value in memory
after BIT shift

1 0000 0001 0000 0010 2

2 0000 0010 0000 0100 4

3 0000 0011 0000 0110 6

Effect of Shifting Bits


Advantages and Disadvantages of
C Programming
Advantages of C Programming Language

1) Building block for many other programming


languages

C is considered to be the most fundamental


language that needs to be studied if you are
beginning with any programming language. Many
programming languages such as Python, C++,
Java, etc are built with the base of the C
language.

2) Powerful and efficient language

C is a robust language as it contains many data


types and operators to give you a vast platform
to perform all kinds of operations.
3) Portable language

C is very flexible, or we can say machine


independent that helps you to run your code on
any machine without making any change or just
a few changes in the code.

4) Built-in functions
There are only 32 keywords in ANSI C, having
many built-in functions. These functions are
helpful when building a program in C.
5) Quality to extend itself
Another crucial ability of C is to extend itself. C language
has its own set of functions in the C library. So, it
becomes easy to use these functions. We can add our own
functions to the C Standard Library and make code
simpler.

6) Structured programming language


C is structure-based. It means that the issues or
complex problems are divided into smaller blocks or
functions. This modular structure helps in easier and
simpler testing and maintenance.

7) Middle-level language
C is a middle-level programming language that means it
supports high-level programming as well as low-level
programming. It supports the use of kernels and drivers
in low-level programming and also supports system
software applications in the high-level programming
language.
8) Implementation of algorithms and data structures
The use of algorithms and data structures in C has made
program computations very fast and smooth. Thus, the C
language can be used in complex calculations and operations
such as MATLAB.
9) Procedural programming language
C follows a proper procedure for its functions and
subroutines. As it uses procedural programming, it becomes
easier for C to identify code structure and to solve any
problem in a specific series of code. In procedural
programming C variables and functions are declared before
use.
10) Dynamic memory allocation
C provides dynamic memory allocation that means you are
free to allocate memory at run time. For example, if you
don’t know how much memory is required by objects in your
program, you can still run a program in C and assign the
memory at the same time.
11) System-programming
C follows a system based programming system. It means the
programming is done for the hardware devices.
So, with this, we are aware of why C considered a very
powerful language and why is it important to know the
advantages of C?
Disadvantages of C Programming language

1. Concept of OOPs
C is a very vast language, but it does not support
the concept of OOPs
(Inheritance, Polymorphism, Encapsulation,
Abstraction, Data Hiding). C simply follows the
procedural programming approach.

2. Run-time checking
In the C programming language, the errors or
the bugs aren’t detected after each line of code.
Instead, the compiler shows all the errors after
writing the program. It makes the checking of
code very complex in large programs.
3. Concept of namespace
C does not implement the concept of
namespaces. A namespace is structured as a
chain of commands to allow the reuse of names
in different contexts. Without namespaces, we
cannot declare two variables of the same name.
But, C programming lacks in this feature, and
hence you cannot define a variable with the
same name in C.

4. Lack of Exception Handling


Exception Handling is one of the most
important features of programming languages.
While compiling the code, various anomalies and
bugs can occur. Exception Handling allows you
to catch the error and take appropriate
responses. However, C does not exhibit this
important feature.
5. Constructor or destructor
C does not have any constructor or destructor.
Constructors & Destructors support basic
functionality of Object Oriented Programming.
Both are member functions that are created as
soon as an object of the class is created. You
will be studying constructor and destructor in
detail later on.

6. Low level of abstraction


C is a small and core machine language that has
minimum data hiding and exclusive visibility that
affects the security of this language.
Applications of C language
 System Programming − C language is used to
develop system software which are close to
hardware such as operating systems, firmware,
language translators, etc.

 Embedded Systems − C language is used in


embedded system programming for a wide range of
devices such as microcontrollers, industrial
controllers, etc.

 Compiler and Interpreters − C language is very


common to develop language compilers and
interpreters.

 Database Systems − Since C language is efficient


and fast for low-level memory manipulation. It is
used for developing DBMS and RDBMS engines.
Applications of C language
 Networking Software − C language is used to
develop networking software such as protocols,
routers, and network utilities.

 Game Development − C language is widely used for


developing games, gaming applications, and game
engines.

 Scientific and Mathematical Applications − C


language is efficient in developing applications where
scientific computing is required. Applications such as
simulations, numerical analysis, and other scientific
computations are usually developed in C language.

 Text Editor and IDEs − C language is used for


developing text editors and integrated development
environments such as Vim and Emacs.
Tokens in C
Tokens in C is the most important element
to be used in creating a program in C. We
can define the token as the smallest
individual element in C.

For example,
we cannot create a sentence without using
words, similarly, we cannot create a
program 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
C Keywords and Identifiers
Keywords and Identifiers in the C language are
the building block of any program.

Keywords are predefined, which means the C


language has a list of words that are Keywords,
while an Identifier is user-defined, which
means you while writing the C language program
can specify identifiers.
Let's see what these two are.

What are Keywords?


Every programming language has some reserved
words that are used internally and have some
meaning for the language, such words are
called Reserved Keywords or just Keywords. C
language has 32 keywords.
Keywords in C Programming Language
auto double int struct

break else long switch

case enum register typedef

char extern return union

const short float unsigned

continue for signed void

default goto sizeof volatile

do if static while
C Identifiers
In the C language identifiers are the names given to
variables, constants, functions, structures, pointers,
or any other user-defined data, to identify them.

Because it's up to the user to define the Identifiers,


hence there are some rules that one has to follow,
which are defined by the C language, to avoid
unnecessary errors in the compiler.
Rules for defining an Identifier:
 An identifier can only have alphanumeric characters(a-z , A-Z ,
0-9) and underscore(_).

 The first character of an identifier can only


contain alphabet(a-z, A-Z) or underscore (_).

 Identifiers are case-sensitive in the C language. For


example, name and Name will be treated as two different
identifiers.

 Keywords are not allowed to be used as Identifiers.

 Identifiers should be written in such a way that it is meaningful,


short, and easy to read.

 The length of the identifiers should not be more than 31


characters.

 No special characters, such as semicolon,


period, whitespaces, slash, or comma (? - + ! @ # % ^ & * (
) [ ] { } . , ; : ’ ‘/ and \. ) are
permitted to be used in or as an Identifier.
Using Identifiers and Keywords

When we declare a variable or any function in


any C language program, to use it we must
provide a name to it, that name is then used
throughout the program,

for example:
int myvariable = 101;

Here myvariable is the name or identifier for


the variable which stores the value 101 in it.
And int is the keyword.

And all of them are tokens.


Example
Let's have another example,
int money;
double salary;

Example of Valid Identifiers:


Here are some valid identifiers,

total, avg1, difference_1;

Example of Invalid Identifiers:


Here are some invalid identifiers,

$myvar; // incorrect
x!y; // again incorrect
Using the Data Types Available in C language

The types of data structures provided by C can be


classified under the following categories:

 Fundamental data types


 Derived data types

Fundamental Data Types


Fundamental data types include the data types at the
lowest level, i.e. those which are used for actual data
representation in the memory. All other data types
are based on the fundamental data types.
Fundamental Data Types
The fundamental data types are:
 char: For characters and strings
 int: For integers
 float: For numbers with decimals such as amounts,
quotients, and salary

Since the preceding data types are fundamental, i.e.


at the machine level, the storage requirement is
hardware dependent. The storage requirements of
the fundamental data types are shown in the following
table.
Data Number of bytes on a Minimum value Maximum value
type 32-bit (HORIZON)
computer
char 1 -128 127

int 4 -2^31 (2^31) - 1

float 4 6 digits of 6 digits of


precision precision
Derived Data Types
Derived data types are based on fundamental data
types, i.e. a derived data type is represented in the
memory as a fundamental data type. Some of the
derived data types with their storage requirements
are shown in the following table.
Data type Number of Minimum value Maximum value
bytes on a32-
bit (HORIZON)
computer
short int 2 -2^15 (2^15) – 1
-32768 to 32767
long int 4 -2^31 (2^31) - 1

double 8 12 digits of 12 digits of


float precision precision

Storage Requirements of Derived Data Types


Defining Data
Definition of memory for any data, both fundamental
and derived data types, is done in the following format:

[data type] [variable name],...;


All data is normally defined in the
beginning of a function.

The definition:
char alph;

defines a memory location of size one byte, of


character type, referred to as alph. Definitions of
various data types are shown in the following table.
Data Data type Memory Size (bytes) Value
definition defined assigned

char a, c; char ac 1 -
1 -

char a = 'Z'; char a 1 Z

int count; int count 4 -

int a, count int a count 4 - 10


=10; 4

float fnum; float fnum 4 -

float fnum1, float fnum1 4 - 93.63


fnum2 = fnum2 4
93.63;

It is evident from the preceding table that the contents


of a variable are undefined, unless it is assigned a value
by initializing it, or by using an input function.
Practice (Just A Minute)
Write the appropriate definitions for defining the
following variables:

1. num to store integers.


2. chr to store a character and assign the character Z to it.
3. num to store a number and assign the value 8.93 to it.
4. i, j to store integers and assign the value 0 to j.
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.
Ex:-
char str[7]=“CIMAGE”;
char str[ ]=“CIMAGE”;
char str[7]={‘C’,’I’,’M’,’A’,’G’,’E’,’\0’};
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:
Ex:-Arithmetic Operators, Relational Operators, Shift
Operators, Logical Operators, Bitwise Operators,
Conditional Operators, Assignment Operator, Misc
Operator.
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. The constant variables can be
initialized once only. The default value of
constant variables are zero.

Variables can be declared as constants by using


the “const” keyword before the datatype of the
variable.

There are two ways of declaring constant:


Using const keyword
Using #define pre-processor
Types of constants in C
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.


Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.


String constant "java", "c++", ".net",
etc.
Example
#include <stdio.h>
int main()
{
const float PI = 3.14159265359;
float radius = 5;
float area = PI*radius*radius;
printf ("area: =%f", area);
return 0;
}

However, changing the value of a constant is


not allowed. The following statement gives a
compiler error −

const float PI = 3.14159265359;


PI=22/7;
You can declare a constant in C without
assigning it a value. But when you try to assign
it a value after words, then the compiler will
throw an error.

const float PI;


PI = 3.14159265359;

Here, you will get this error message −

error: assignment of read-only variable 'PI'


Defining a Constant Using the
#define Directive
Using the #define preprocessor directive is also an
effective method to define a constant.
Here is its syntax −
#define name = value

Take a look at the following example:

#define PI = 3.14159265359

difference between the const and #define.


1)The constants created by the #define directive
are not handled by the compiler. Instead, they
behave as macros, whose values are substituted
at the runtime.
2)The other notable difference is that you need
not mention the data type of the value to be
assigned to the constant when using
the #define directive.
Example
Example: Define a Constant Using the #define

#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main()
{
int area;
area = LENGTH * WIDTH;
printf("length: %d width: %d", LENGTH, WIDTH);
printf("%c", NEWLINE);
printf("value of area : %d", area);
return 0;
}
Types of Variables in C Language

1. Local Variable in C

Local variables are declared and initialized at the


start of a function or block and allocated memory
inside that execution scope.

The statements only inside that function can access


that local variable. Such variables get destroyed when
the control exits from the function.
Example
#include <stdio.h>
void local();

void main()
{
int a = 22, b = 44;

local();

printf("Values in the main() function a = %d and b = %d\n", a, b);


}

void local()
{
int a = 50, b = 80;
printf("Values in the local() function a = %d and b = %d\n", a, b);
}

Output

Values in the local() function a = 50 and b = 80


Values in the main() function a = 22 and b = 44
2. Global Variable in C
The global variable in C is defined outside of any
function and is therefore accessible to all functions.

Global variables in C are initialized when the program


starts, and until the program exits, these variables
remain stored in the memory.

#include <stdio.h>
int a = 20; // Global declaration
void global();

void main() {
printf("In main() function a = %d\n", a); // Prints 20
global();
a = a + 15; // Uses global variable
printf("In main() function a = %d\n", a); // Prints 55
}

void global() {
a = a + 20; // Uses global variable
printf("In global() function a = %d\n", a); // Prints 40
}
2. Global Variable in C
Output:

In main() function a = 20
In test() function a = 40
In main() function a = 55

In the above code, a global variable, a=20 is declared.


It is accessed by both the functions, global() and
main().

The modification of a by the global() function affects


the value of a in the main() function as well.

The global() function operates on the modified value


of a.
Using boolean variable in C?
The bool data type is one of the fundamental data types
in C. It is used to hold only two values i.e. true or false.
The C program returns boolean values as integers,
0 and 1. The boolean meaning of these integers are:

 0 indicates a false value


 1 (or any other number not equal to 0) indicates true
value.

As they return boolean values, we need to use the


format specifier, “%d” to print the boolean values.

In C language, the bool data type is not a built-in data


type. The C99 standard for C language introduced
boolean in C.

It is necessary to import the header file, stdbool.h to


declare boolean variables to use boolean value in C.
Example
#include <stdio.h>
#include <stdbool.h>

int main()
{
bool x=false, y=true; // variable initialization.

printf("%d\n",x);
printf("%d\n",y);
return 0;
}
Boolean expressions:

The user can use Boolean expressions to evaluate


conditions and make decisions in their code.

For example:

#include <stdbool.h>
bool isSunny = true;
bool isRaining = false;
int main()
{
if (isSunny && !isRaining)
{
printf("It's a perfect day for a picnic!\n");
}
Return 0;
}
Example :
#include <stdio.h>
int main()
{
const int a;
const int b = 12;
printf("The default value of variable a : %d", a);
printf("The value of variable b : %d", b);
return 0;
}
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.

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

Asterisk (*): This symbol is used to


represent pointers and also used as an
operator for multiplication.

Period (.): It is used to access a member of a


structure or a union.
Identifying the Structure of C Functions

In C language, the functions can be categorized


in the following categories:

 Single-level functions
 Multiple-level functions

Single-Level Functions

The following function is a single-level


function:

main()
{
/*print a message*/
printf("Welcome to C");
}
In a C program, main() is always the first function to be
executed by the computer and should be present in all
programs. It is like any other function available in the C
library, or like one developed by a user.
Parenthesis () are used for passing parameters (if any) to
a function.

The brackets {} mark the beginning and end of a function


and are mandatory in all functions. /* */ enclose a
comment line in a function, which is useful for
documenting various parts of a function. The comment line
may be in a separate line or part of an executable line.
The comment line is optional. The semicolon is used for
marking the end of an executable line.

In the preceding code, printf() is a C function for printing


(displaying) constant or variable data and
Welcome to C is the parameter passed to it. This function
will be discussed in detail in due course.
Just A Minute
Identify any erroneous or missing component(s) in the following
functions:
1) main()
{
printf("This function seems to be okay")
}

2) main()
{
/*print a line*/
printf("This function is perfect";
}

3) main()
}
printf("This function seems to be okay")
{

4) main()
{
This is a perfect comment line printf("Is it okay?");
}
Multiple-Level Functions
The following is an example showing
functions at multiple levels - one function
being called by another function

main()
{
/*print a message*/
printf("Welcome to C.");
disp_msg();
printf("for good learning.");
}

disp_msg()
{
/*print another message*/
printf("All the best ");
}
The output of the preceding program is:

Welcome to C. All the best for good learning.

In the preceding program, .. disp_msg()is a


user-defined function that is called from the
main() function. The () can be used for passing
values to functions, depending on whether the
receiving function is expecting any parameter.

As mentioned earlier, executable lines are


terminated by a semi-colon (;). A statement
calling/executing a function needs to be
terminated by a semi-colon, but a statement
marking the beginning of a function-definition
does not have a semi-colon at the end.
Using the Input-Output Functions
The C environment assumes that the standard input
device (Keyboard), the standard output device (VDU),
and the standard error device (VDU) are always linked
to the environment.

For standard input-output operations, the C


environment uses stdin, stdout, and stderr as
references for accessing the devices.

The C language, as such, does not provide for any


input-output operations as part of the language.

They exist as functions written in C and are available


in the standard C library along with other functions.
These input and output functions may be used by any
programmer.

Any input or output operation takes place as a stream


of characters.
The standard input-output functions may be dealt with
character-based input-output functions and string-
based (stream of characters) input-output functions.

The standard input-output functions are buffered, i.e.


each device has an associated buffer through which
any input or output operation takes place. After an
input operation from the standard input device, care
must be taken to clear the standard input buffer lest
the previous contents of the buffer interfere with
subsequent input operations. The output buffer is
cleared only if a newline character is used or if an
input function is used or the buffer is explicitly
cleared.
Character-Based Input-Output Functions
The following function accepts a single character
from the keyboard (standard input device) and
displays it on the VDU (standard output device):

#include<stdio.h>
/*function to accept and display a character*/
main()
{
char alph;
alph=getc(stdin); /*Accept character*
fflush(stdin); /*Clears the stdin buffer*/
putc(alph,stdout); /*Displays a character*/
}
The function main() first defines a memory location,
alph, of char type, and then invokes the functions
getc() and putc().
The function getc() accepts as parameter the
reference of device, and allows one character
to be read from this device during program
execution. In this case, the device is stdin.
The character read is returned and assigned to
alph.

The function putc() accepts as parameters the


character to be output, and the reference of
the output device (stdout in this case) to which
one character is to be output.

The function fflush() clears the buffer


associated with a specified input or output
device (stdin in this case). It is a good
programming practice to clear the buffer even
if there are no subsequent input operations in a
function.
The statement #include <stdio.h> includes at
the time of compilation, the contents of the
standard input-output file, stdio.h, which
contains definitions of stdin, stdout, and
stderr. Whenever the references stdin, stdout,
and stderr are used in a function, this
statement has to be used.

Practice
Write a function to input a character and
display the character input twice.
The function to input and display a character, discussed
earlier, can also be written as:

/*function to input and display a character using the */


/*function getchar() */

#include<stdio.h>
main()
{
char c;
c=getchar();
fflush(stdin);
putchar(c);
}

In the preceding function, getchar() is equivalent to


getc(stdin) and putchar(c) is equivalent to putc(c, stdout).
Practice
Write a function to accept and store two characters in
different memory locations, and to display them one after
the other using the functions getchar() and putchar().
String-Based Input-Output Functions

The functions getc(), getchar(), putc(), and putchar()


perform character-based input-output. C language
provides the functions gets() and puts() for string-
based input-output, as shown in the following program:

/*function to accept and display a string*/


#include<stdio.h>
main()
{
char in_str[21];

puts(“Enter a string of max 20 characters”); /*display


prompt*/

gets(in_str); /*accept string*/


fflush(stdin); /*clear the buffer*/
puts(in_str); /*display input string*/
}
It is a good programming practice to prompt for input
by displaying a message before an input. This has been
done by using the puts() function in this program.

The function puts() accepts, as parameter, a string


variable or a string constant (enclosed in double
quotes) for display-on the standard output.

The puts() function causes the cursor to jump to the


next line after printing the string. The function gets()
accepts the string variable into the location where the
input string is to be stored.
Compilation Process of C Programe
Compiler, Linker, Assembler, and Loader

Compiler :
A compiler is a specialized system tool that
translates a program written in a specific
programming language into the assembly language
code. The assembly language code is specific to each
machine and is governed by the CPU of the machine.

Assembler:
The assembler enters the arena after the compiler
has played its part. The assembler translates our
assembly code to the machine code and then stores
the result in an object file. This file contains the
binary representation of our program.
Moving further, the assembler gives a memory
location to each object and instruction in our
code. The memory location can be physical as well as
virtual. A virtual location is an offset that is relative
to the base address of the first instruction.
Linker:
Next, we move to the linker module. The linker spawns
to action after the assembler has done its
job. The linker combines all external programs (such
as libraries and other shared components) with our
program to create a final executable. At the end of
the linking step, we get the executable for our program.
So, the linker takes all object files as input, resolves all
memory references, and finally merges these object
files to make an executable file.

Loader:
The loader is a specialized operating system module
that comes last in the picture. It loads the final
executable code into memory.
Afterward, it creates the program and data stack.
Then, it initializes various registers and finally gives
control to the CPU so that it can start executing the
code.
Practice
1) Write a function that prompts for and
accepts a name with a maximum of 25
characters, and displays the following message.

Hello. How are you? (name)

2) Write a function that prompts for a name


(up to 20 characters) and address (up to 30
characters) and accepts them one at a time.
Finally, the name and address are displayed in
the following way.

Your name is: (name)


Your address is: (address)
C Increment and Decrement Operators
C programming has two operators increment ++ and
decrement -- to change the value of an operand (constant
or variable) by 1.

Increment ++ increases the value by 1 whereas


decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only
operate on a single operand.

// Working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
C 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: Arithmetic Operators
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}
C Assignment Operators
An assignment operator is used for assigning a
value to a variable. The most common
assignment operator is =

Operator Example Same as

= a =b a = b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example : Assignment Operators
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Using Operator Precedence
C, defines a set of rules for using operators.
These rules specify the order in which the
expression will be evaluated, when there are
multiple operators in an expression.

For example,

if there are two operators in an expression,


such as + and *, then the multiplicative
arithmetic operator will be evaluated first as it
has higher precedence than the additive
arithmetic operator.

However, precedence rules can be overridden


by using the parentheses.
Identifying the Order of Precedence

Consider the expression, 45+90/5*6.

To compute the result of the expression, each


operator in an expression needs to be evaluated
in a predetermined order called operator
precedence.

Operators with a higher precedence are applied


before operators with a lower precedence.

The following table lists the operator


precedence with their categories sorted from
the highest precedence to the lowest
precedence.
Implementing Precedence Using
Parentheses
Parentheses are often used to obtain the desired results
as they can override the order of precedence. For
example, consider the following code snippet:

3 * 5 + 2;
In the preceding code snippet, the result of the
expression will be 17, because first 3 will be multiplied by
5, and then 2 will be added to the result. In this case,
precedence of the * operator is higher than the +
operator.
However, you can apply the parenthesis on the preceding
code, as shown in the following code snippet:

3 * (5 + 2);
In the preceding code snippet, the result of the
expression will change to 21 as first 2 will be added to 5,
and then result will be multiplied by 3. In this case, the
precedence of parenthesis is higher than the precedence
of operator.
Just A Minute (JAM)

#include<stdio.h>
main()
{
int i=45+90/5*6;
printf("%d",i);
}
Just A Minute (JAM)
#include<stdio.h>
main()
{
int a=5,i;

i=++a + ++a + a++;


i=a++ + ++a + ++a;
a=++a + ++a + a++;

printf("a=%d\n",a);
printf("i=%d\n",i);
}
Escape Sequence in C
An escape sequence in C language is a sequence
of characters that doesn't represent itself
when used inside string literal or character.

It is composed of two or more characters


starting with backslash \.

For example: \n represents new line.


Escape Sequence Name Description
It is used to generate
\a Alarm or Beep a bell sound in the C
program.
It is used to move the
\b Backspace
cursor backward.
It moves the cursor to
\n New Line the start of the next
line.
It moves the cursor to
\r Carriage Return the start of the
current line.
It inserts some
whitespace to the left
\t Horizontal Tab of the cursor and
moves the cursor
accordingly.
Use to insert
\\ Backlash
backslash character.
It is used to display a
\’ Single Quote
single quotation mark.
It is used to display
\” Double Quote double quotation
marks.
It represents the NLL
\0 NULL
character.
printf() and scanf() in C
The printf() and scanf() functions are used for
input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h
(header file).

printf() function
The printf() function is used for output. It
prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c


(character), %s (string), %f (float) etc.
scanf() function
The scanf() function is used for input. It reads the
input data from the console.
scanf("format string",argument_list);
Program to print cube of given number.

#include<stdio.h>
int main(){
int num;
printf("enter a number:");
scanf("%d",&num);
printf("cube of number is:%d ",num*num*num);
return 0;
}
Format Specifiers for I/O
Data Type Format Specifier

int %d
char %c
float %f
double %lf
long double %Lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
sizeof operator in C
 sizeof is a much-used operator in the C. It
is a compile-time unary operator which can
be used to compute the size of its operand.

 The result of sizeof is of the unsigned


integral type which is usually denoted by
size_t.

 Sizeof can be applied to any data type,


including primitive types such as integer and
floating-point types, pointer types, or
compound data types such as Structure,
union, etc.
Usage of sizeof() operator
// C Program To demonstrate sizeof operator
#include <stdio.h>
int main()
{
printf("%d\n", sizeof(char));
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(float));
printf("%d\n", sizeof(double));
printf("%d\n", sizeof(long double));
printf("%d\n", sizeof(short int));
printf("%d\n", sizeof(unsigned int));
printf("%d\n", sizeof(long int));
printf("%d\n", sizeof(long long int));
printf("%d\n", sizeof(unsigned long int));
printf("%d\n", sizeof(unsigned long long int));
return 0;
}
C Numeric I/O
#include <stdio.h>
int main()
{
int testInteger;
float num1;
double num2;

printf("Enter an integer: ");


scanf("%d", &testInteger);
printf("Enter a Fractional number: ");
scanf("%f", &num1);
printf("Enter another fractional number: ");
scanf("%lf", &num2);

printf("num1 = %f\n", num1);


printf("num2 = %lf", num2);
printf("Number = %d",testInteger);
return 0;
}
I/O Multiple Values
#include <stdio.h>
int main()
{
int a;
float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs


scanf("%d%f", &a, &b);

printf("You entered %d and %f", a, b);


return 0;
}
#include<stdio.h>
main()
{
char name[31],add[51],f[31],coll[51],g;
int n1,n2;
printf("Enter two numbers to add\t");
scanf("%d%d",&n1,&n2);
getchar();
printf("Enter your Name :");
scanf("%[^\n]%*c", name);
printf("Enter Your gender(1 character) ");
scanf("%c",&g);
getchar();
printf("Enter Colege Name ");
gets(coll);
printf("Enter your Fathers Name :");
fgets(f,31,stdin);
printf("Enter your Address :");
scanf("%[^\n]s", add);

printf("Your name is %s\n",name);


printf("Your Gender is %c \n",g);
printf("Your College name is %s\n",coll);
printf("Your Fathers name is %s\n",f);
printf("Your Address is %s\n",add);
printf("Sum of two numbers is\t%d",n1+n2);
}
C Character I/O
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed


printf("ASCII value is %d.", chr);

return 0;
}
Using Constructs
There are two types of constructs in C language:
 Conditional constructs
 Loop constructs

Conditional Constructs

Most of the conditional constructs available in C


are similar to those available in other third
generation languages. The relational operators
required for evaluating the conditions are similar
to those in the other languages, though the
symbols are slightly different. The following
table contains the relational operators with their
meaning.
C Relational Operators
Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= 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 5 <= 3 is evaluated to 0
Example : Relational Operators
// Working of relational operators
#include <stdio.h>
int main()
{
int a = 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);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
Logical Operators in C
Logical operators in C are used to combine
multiple conditions/constraints. Logical
Operators returns either 1 or 0, it depends on
the expression result true or false.

In C programming for decision-making, we use


logical operators. We have 3 major logical
operators in the C language:

 Logical AND (&&)


 Logical OR (||)
 Logical NOT (!)
1. Logical AND Operator
If both operands are non zero then the condition
becomes true. Otherwise, the result has a value of 0.
The return type of the result is int. Below is the truth
table for the logical AND operator.
Example
// C program for Logical AND Operator

#include <stdio.h>
int main()
{
int a = 10, b = 20;
if (a > 0 && b > 0)
{
printf("Both values are greater than 0\n");
}
else
{
printf("Both or any one values are less
than 0\n");
}
return 0;
}
2. Logical OR Operator
The condition becomes true if any one of them is non-zero.
Otherwise, it returns false i.e, 0 as the value. Below is the truth
table for the logical OR operator.
Example
// C program for Logical OR Operator
#include <stdio.h>

int main()
{
int a = -1, b = 20;

if (a > 0 || b > 0)
{
printf("Any one of the given value is "
"greater than 0\n");
}
else
{
printf("Any one values are less than or
equals to 0\n");
}
return 0;
}
3. Logical NOT Operator
If the condition is true then the logical NOT operator will
make it false and vice-versa. Below is the truth table for the
logical NOT operator.
Example
// C program for Logical NOT Operator
#include <stdio.h>
int main()
{
int a = 10, b = 20;

if (!(a > 0 and b > 0))


{
// condition returned true but
// logical NOT operator changed it to false
printf("Both values are greater than 0\n");
}
else
{
printf("Both or any one values are less than
or equal to 0\n");
}
return 0;
The sizeof operator
The sizeof is a unary operator that returns the
size of data (constants, variables, array,
structure, etc).

#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));

return 0;
}
Working with Conditional Constructs

In your daily life, you take various decisions that are


based on certain conditions.

For example,
if it is raining, you will take an umbrella. In the same
way, you can incorporate the decision making
techniques in the C programming language. The
decision making technique can be implemented in the C
programs by using the following conditional constructs:

 The if construct
 The if…else construct
 Nesting of if ... else Statements
 The else if Ladder
 The switch construct
 The ?: Operator.
The if statement
It is one of the simplest decision-making
statement which is used to decide whether a
block of C code will execute if a certain
condition is true.
Example
//C Program to demonstate the use of if statement
.
void main()
{
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
{
puts("Age is greater than 18");
}
puts(“Part of Main()”);
}
C if-else Statement
An if….else statement includes two blocks that are if
block and else block. It is the next form of the control
statement, which allows the execution of C code in a more
controlled way. It is used when you require to check two
different conditions and execute a different set of codes.
The else statement is used for specifying the execution
of a block of code if the condition is false.

Syntax

if (condition)
{
// block of code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}
If the condition is true, then the statements inside if
block will be executed, but if the condition is false,
then the statements of the else block will be
executed.
//A C Program to demonstrate the use of
else statement.
//It is a program of odd and even number.
void main()
{
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0)
{
puts("even number");
}
else
{
puts("odd number");
}
}
The if...else Construct
The following function shows the use of
the if..else conditional construct:

#include<stdio.h> main()
{
char chr;
puts(“Enter a character”);
chr=getchar();
fflush(stdin);
if(chr==’A’)
puts(“Character is A”);
else
puts(“Character is not A”);
}
In the preceding example, if the input
character is A, the message displayed is
Character is A, otherwise the message Character
is not A is displayed. Also, note that the
condition has to be specified within
parenthesis.

If, however, the operator = is used instead of


the == operator, the statement is executed as
an assignment.

For example,
if the statement if (chr == 'A') was written as if
(chr = 'A') then chr would have got the value A,
and it being non-zero, the condition would be
evaluated as TRUE. Thus, the message Character
is A would have been printed regardless of the
input.
The function may also be written in the
following way:
#include<stdio.h>
main()
{
char chr;
puts(“Enter a character”);
chr=getchar();
fflush(stdin);

if(chr!=’A’)
puts(“Character is not A”);
else
puts(“Character is A”);
}

The operator != is an equivalent of not equal to, and is


written with no space between ! and =. The following
function uses a nested if...else construct to check if an
input character is in upper-case or in lower-case:
C Nested if statement
The nested if statement represents the if
block within another if block. Here, the inner if
block condition executes only when outer if
block condition is true.

Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
//C Program to demonstrate the use of Nested If Statement.
void main()
{
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
puts("You are eligible to donate blood");
}
}
}
#include<stdio.h>
main()
{
char inp;
puts(“Enter a character”);
inp=getchar();
fflush(stdin);
if(inp>=’A’)
if(inp<=’Z’)
puts(“Upper Case”);
else if(inp>=’a’)
if(inp<=’z’)
puts(“Lower Case”);
else
puts(“Input character > z”);
else
puts(“Input character > Z but less than a”);
else
puts(“Input character less than A”);
}
C if-else-if ladder Statement
The if-else-if ladder statement executes one
condition from multiple statements.

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
}
//C Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade a
nd A+.
void main()
{
int marks=65;

if(marks<50){
printf("fail");
}
else if(marks>=50 && marks<60){
printf("D grade");
}
else if(marks>=60 && marks<70){
printf("C grade");
}
else if(marks>=70 && marks<80){
printf("B grade");
}
else if(marks>=80 && marks<90){
printf("A grade");
}else if(marks>=90 && marks<100){
printf("A+ grade");
}
else
{
printf("Invalid!");
}
}
#include <stdio.h>
/* function to determine if input is a vowel */
main ()
{
char in_chr;
puts ("Enter a character in lower case:”);
in_chr = getchar ();
fflush (stdin);
if(in_chr== ‘a’)
puts ("Vowel a");
else if (in_chr == ‘e')
puts ("Vowel e");
else if (in_chr == ‘i')
puts ("Vowel i");
else if (in_chr == ‘o')
puts ("Vowel o");
else if (in_chr == ‘u')
puts ("Vowel u");
else
puts(“The character is not a vowel”);
The switch construct
The switch statement in C is an alternate to if-
else-if ladder statement which allows us to
execute multiple operations for the different
possible values of a single variable called switch
variable.

Here, We can define various statements in the


multiple cases for the different values of a
single variable.

The syntax of switch statement in c language is


given below:

In other words, the switch statement tests the


equality of a variable.
Syntax
switch(expression)
{
case value1:
//code to be executed;
break; //optional

case value2:
//code to be executed;
break; //optional
......

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

}
Rules for switch statement in C language

1) The switch expression must be of an integer


or character type.

2) The case value must be an integer or


character constant.

3) The case value can be used only inside the


switch statement.

4) The break statement in switch case is not


must. It is optional. If there is no break
statement found in the case, all the cases will be
executed present after the matched case. It is
known as fall through the state of C switch
statement.
#include<stdio.h>
main()
{
//Specifying month number
int month=9;
//Switch statement
switch(month)
{
//case statements within the switch block
case 1: puts("1 - january"); break;
case 2: puts("2 - February"); break;
case 3: puts("3 - March"); break;
case 4: puts("4 - April"); break;
case 5: puts("5 - May"); break;
case 6: puts("6 - June"); break;
case 7: puts("7 - July"); break;
case 8: puts("8 - August"); break;
case 9: puts("9- September"); break;
case 10: puts("10 - October"); break;
case 11: puts("11 - November"); break;
case 12: puts("12 - December"); break;
default : puts("Invalid Choice");
}
}
Using Ternary Operator
We can also use ternary operator (? :) to
perform the task of if...else statement. It is a
shorthand way to check the condition. If the
condition is true, the result of ? is returned.
But, if the condition is false, the result of : is
returned.

Example:
#include<stdio.h>
main()
{
int number=13;
//Using ternary operator
(number%2==0)?puts("even number"):puts("odd
number");
}
C Program to swap two numbers
int main()
{
int a = 5, b = 10, temp;

printf( "Before swapping.\n" );


printf(“a = %d , b = %d”,a,b);

temp = a;
a = b;
b = temp;

printf( “After swapping.\n" );


printf(“a = %d , b = %d”,a,b);
return 0;
}
C Program to swap two numbers
without third variable
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);

a=a+b; //a=30 (10+20)


b=a-b; //b=10 (30-20)
a=a-b; //a=20 (30-10)

printf("\nAfter swap a=%d b=%d",a,b);

return 0;
}
Left Shift(<<) and Right
Shift(>>) Operators in C
In C, left shift (<<) and right shift (>>)
operators are binary bitwise operators that
are used to shift the bits either left or right
of the first operand by the number of
positions specified by the second operand
allowing efficient data manipulation.
Left Shift (<<) Operators
The left shift(<<) is a binary operator that
takes two numbers, left shifts the bits of the
first operand, and the second operand decides
the number of places to shift.

In other words, left-shifting an integer “a” with


an integer “b” denoted as ‘(a<<b)’ is equivalent
to multiplying a with 2^b (2 raised to power b).

Syntax
varName << no_of_position
a << b;

where,
a is the integer value to be shifted.
b specifies how many positions to shift the bits.
Example:
Let’s take a=100; which is 01100100 in Binary
Form.

Now, if “a is left-shifted by 2”

i.e a=a<<2 then a will become a=a*(2^2).

Thus, a=100*(2^2)=400 which can be written


as 0110010000.
Example :
#include <stdio.h>
int main() {
int x = 100;
int y;
printf("Enter number of positions for the bits to shift
to the left : ");
// Taking input of the second operand.

scanf("%d", &y);
printf("After performing left shift operation : ");

printf("%d << %d = %d", x, y, x << y);


return 0;
}
Applications of Left Shift Operator
Multiplication by Powers of Two: Left shifting
a number by n positions is equivalent to
multiplying it by 2^n and is much faster than
normal multiplication

Efficient Calculations: Used in performance-


critical applications where arithmetic
operations need to be fast.

Bit Manipulation: Common in low-level


programming, such as embedded systems and
hardware interfacing.
Right Shift(>>) Operators
Right Shift(>>) is a binary operator that takes
two numbers, right shifts the bits of the first
operand, and the second operand decides the
number of places to shift.

In other words, right-shifting an integer “a”


with an integer “b” denoted as ‘(a>>b)‘ is
equivalent to dividing a with 2^b.

Syntax
operand >> number
a >> b;

where,
a is the integer value to be shifted.
b specifies how many positions to shift the bits.
Example:
let’s take a=8;
which is 1000 in Binary Form. Now, if “a is
right-shifted by 2”
i.e a=a>>2 then a will become a=a/(2^2).

Thus, a=a/(2^2)=2 which can be written as 10.


Explanation
The below image illustrates the step-by-step
shifting for 8 >> 2
Example
#include <stdio.h>
int main() {
int x = 100;
int y;

printf("Enter number of positions for the bits to


Right to the left : ");
// Taking input of the second operand.

scanf("%d", &y);
printf("After performing Right shift operation : ");

printf("%d >> %d = %d", x, y, x >> y);


return 0;
}
Loop Constructs
Looping Statements in C execute the sequence
of statements many times until the stated
condition becomes false.

A loop in C consists of two parts, a body of a


loop and a control statement. The control
statement is a combination of some conditions
that direct the body of the loop to execute
until the specified condition becomes false.

The purpose of the C loop is to repeat the same


code a number of times.
Why looping?
The looping simplifies the complex
problems into the easy ones.

It enables to alter the flow of the


program so that instead of writing the
same code again and again, we can
execute the same code for a finite
number of times.

For example,
if we need to print ‘Hello Friends’ 10-
times then, instead of using the printf
statement 10 times, we can use printf
once inside a loop which runs up to 10
iterations.
What are the advantages of Looping?

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


those are given below:
 while
 Do while
 for
Essential components of a loop
Counter

 Initialization of the counter with initial


value

 Condition to check with the optimum value


of the counter

 Statement(s) to be executed by iteration

 Increment/decrement
while loop in C
The while loop in c is to be used in the scenario
where the block of statements is executed in
the while loop until the condition specified in
the while loop is satisfied. It is also called a
pre-tested loop.

The syntax of while loop in c language is


given below:

initialisation;
while(condition)
{
block of statements to be executed ;
increment ;
}
Flowchart of while loop
Write a C-program to print 10 natural
numbers

#include<stdio.h>
main()
{
int i=1;
while(i<=10)
{
printf("%d\n",i);
i=i+1;
}
}
Program to print table for the given
number using while loop in C
#include<stdio.h>
main()
{
int i=1,number,b;
printf("Enter a number:");
scanf("%d",&number);

while(i<=10)
{
b=number*i;
printf("%d\n", b);
i=i+1;
}
}
The following function shows the use of the while
construct in accepting an input as y or n only. Any other
input is rejected by the function until a valid input is
provided. Consider the following example:
#include<stdio.h>
main()
{
char inp, valid=’n’;
while(valid==’n’)
{ /*repeat as long as condition is TRUE*/
valid=’ ’;
puts(“Enter y or n”);
inp=getchar();
fflush(stdin);

if(inp==’y’)
puts(“Valid input”);
else if(inp==’n’)
puts(“Valid input”);
else
{
valid=’n’;
puts(“Invalid data”);
}
}
}
The following function uses a while construct to display menu and to
accept and display menu choices until a valid choice has been entered:

#include<stdio.h>
/* function to generate a menu, to accept and display */
/* choice using while loop construct */
main ()
{
char chc, ok; ok = ‘y’ ;

while (ok == 'y')


{ /* beginning of while block */
puts(“Menu”);
puts(“1. Create a Directory”);
puts (“2. Delete a Directory”);
puts (“3. Show a Directory”);
puts (“4. Exit”);
puts(" "); /* display a blank line*/
chc = getchar ();
fflush (stdin);

switch (chc)
{
case ‘1’: puts (“Choice is 1”); break;
case ‘2’: puts (“Choice is 2”); break;
case ‘3’: puts (“Choice is 3”); break;
case ‘4’: puts (“Choice is 4”); break;
default: puts(“Invalid Choice”);
ok=’n’;
} /*end of switch block*/
} /*end of while block*/
}
The following function draws a box with a dimension
of 5 rows with side walls using a while statement:

#include<stdio.h>
/*function to draw a box of 5 */
main()
{
int row=0;
puts("---------"); /*Top line*/
while(row<5)
{
puts("| |");
/*Ten lines with side boundary*/
row=row+1;
}
puts("---------"); /*bottom line*/
}
Write a program in C to accept a number and revere it..

#include <stdio.h>
int main()
{
int n, r = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
fflush(stdin);

printf("Reverse of the number %d is := ", n);


while (n >0)
{
r=n%10;
printf("%d",r);
n=n/10;
}
return 0;
}
Program to Check number is Palindrome
#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;

// reversed integer is stored in reversed variable


while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
// palindrome if orignal and reversed are equal
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}
Armstrong Number in C
Armstrong number is a number that is equal to the
sum of cubes of its digits. For example 0, 1, 153, 370,
371 and 407 are the Armstrong numbers.

Let's try to understand why 153 is an Armstrong


number.

153 = (1*1*1)+(5*5*5)+(3*3*3)

where:

(1*1*1)=1
(5*5*5)=125
(3*3*3)=27

So:

1+125+27=153
#include<stdio.h>
int main()
{

int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;

while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}

if(temp==sum)
printf("armstrong number ");
else
printf("not armstrong number");

return 0;
}
do-while loop in C
 The do...while loop construct, like the while loop
construct, is used in situations where the number
of iterations to be performed is not known, and is
dependent on a condition, which changes within the
loop-body.

 Also, iterations are to be performed until the


specified loop condition becomes FALSE.

 It is also called post tested loop

 It differs from the while loop in that the body


of the loop is executed at least once (mostly
menu driven programs), and the condition is
evaluated for subsequent executions.
do-while loop in C

The syntax of do-while loop in c language is


given below:

do
{
code to be executed ;
increment;

} while(condition);
difference between the while loop and
the do...while loop
The following program uses the do...while loop for the menu
program written earlier using the while loop:

#include<stdio.h>
/* function to generate a menu, to accept and display */
/* choice using while loop construct */
main ()
{
char chc, ok;
do
{ /* beginning of do….while block */
ok='y'; /*initialize ok*/
puts("Menu");
puts("1. Create a Directory");
puts("2. Delete a Directory");
puts("3. Show a Directory");
puts("4. Exit");
puts(" "); /* display a blank line*/
chc = getchar();
fflush(stdin);

switch (chc)
{
case '1': puts ("Choice is 1"); break;
case '2': puts ("Choice is 2"); break;
case '3': puts ("Choice is 3"); break;
case '4': puts ("Choice is 4"); break;
default: puts("Invalid Choice");
ok='n';
} /*end of switch block*/
} while(ok=='y'); /*end of while block*/
}
Exercise
1) Write a function to accept characters from
the keyboard until the character ‘!’ is input,
and to display whether the total number of
non-vowel characters entered is more than,
less than, or equal to the total number of
vowels entered.

2) Write a function that accepts a number from


0 to 9, along with a string. The string should
then be displayed the number of times
specified.
Write a function to check entered number is a Prime number.

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

int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

// 0 and 1 are not prime numbers change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;

for (i = 2; i <= n / 2; ++i) {


// if n is divisible by i, then n is not prime change flag to 1 for non-prime number
if (n % i == 0)
{
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
Exercise
3) Write a program, which allows the user to
enter characters until the input is '0'. Each
time a character is entered, the program
should display whether it is greater/lesser
than or equal to the previous character
entered.

4) Write a function to accept 20 characters


and display whether each character input is a
digit, a lower-case alphabet, or an upper-case
alphabet.

5) Write a function that accepts 25 characters


and at the end, displays the smallest and the
largest of all characters.
for Loop in C
 The for loop in C Language provides a
functionality/feature to repeat a set of
statements a defined number of times.

 The for loop is in itself a form of an entry-


controlled loop.

 Unlike the while loop and do…while loop, the


for loop contains the initialization, condition,
and increment/decrement statements as part
of its syntax.

 It is mainly used to traverse arrays, vectors,


and other data structures.
Syntax: For Loop
for (initialization expr; test expr; increment/Decrement exp)
{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop

Java for loop is divided into various parts


as mentioned below:

 Initialization Expression
 Test Expression
 Increment/Decrement Expression
How does a For loop work?
Control falls into the for loop.

1. Initialization is done
2. The flow jumps to Condition
3. Condition is tested.
1. If the Condition yields true, the flow goes into the
Body
2. If the Condition yields false, the flow goes outside
the loop
4. The statements inside the body of the loop get
executed.
5. The flow goes to the Increment/Decrement Exp

6. Updation takes place and the flow goes to Step


3 again

7. The for loop has ended and the flow has gone
outside.
The following function uses a for loop
to accept a string and display 10 times
timesstrings entered from the
#include<stdio.h>
/*function
keyboard:to accept and display 10 strings*/
main()
{
char str1[50]; int times;
for(times=0;times<10;times=times+1)
{
puts(“Enter string”);
gets (str1);
fflush (stdin);
puts(str1);
}
}

There are three components of the loop control statement


of a for construct, namely:

Initialization, i.e. times = 0


Loop condition, i.e. times < 10, and
Reinitialization (increment/decrement) i.e. times = times +1
Function to accept a number and
reverse it.
#include <stdio.h>
int main()
{
int n, r = 0;

printf("Enter a number to reverse\n");


scanf("%d", &n);
fflush(stdin);

printf("Reverse of the number %d is := ", n);


while (n >0)
{
r=n%10;
printf("%d",r);
n=n/10;
}
return 0;
}
What is the Fibonacci Series?
The Fibonacci sequence is a type series where each
number is the sum of the two that precede it.

It usually starts from 0 and 1. The Fibonacci sequence


is given by 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and
so on.

The numbers in the Fibonacci sequence are also called


Fibonacci numbers.
Example:
Input1: 10
Output1:0 1 1 2 3 5 8 13 21 34
Explanation:
1st term = 0
2nd term = 1
3rd term = 1st term + 2nd term = 0 + 1 = 1
4th term = 2ndterm + 3rd term = 1 + 1 = 2
And so on……
#include <stdio.h>

int main() {
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i) {


printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}

return 0;
}
Practice
1) Write a function to accept five characters
from the character set, and to display
whether the number of lower-case
characters is greater than, less than, or
equal to number of upper-case characters.
Display an error message if the input is not
an alphabet.

2) Modify the function to accept characters


endlessly until the character ! is input from
keyboard.
goto Statement in C
The C goto statement is a jump statement which is
sometimes also referred to as an unconditional
jump statement. The goto statement can be used to
jump from anywhere to anywhere within a function.

Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to


go to or jump to the statement marked as a label.
Here, the label is a user-defined identifier that
indicates the target statement. The statement
immediately followed after ‘label:’ is the destination
statement. The ‘label:’ can also appear before the ‘goto
label;’ statement in the above syntax.
Examples:
Type 1: In this case, we will see a situation
similar to as shown in Syntax1 above. Suppose we
need to write a program where we need to check
if a number is even or not and print accordingly
using the goto statement. The below program
explains how to do this:

// C program to check if a number is


// even or odd using goto statement
#include <stdio.h>
// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}

int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}
Type 2:
In this case, we will see a situation similar to as
shown in Syntax2 above. Suppose we need to
write a program that prints numbers from 1 to
10 using the goto statement. The below program
explains how to do this.
// C program to print numbers from 1 to 10 using goto statement
#include <stdio.h>

// function to print numbers from 1 to 10


void printNumbers()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
}

int main()
{
printNumbers();
return 0;
}
Disadvantages of Using goto Statement

The use of the goto statement is highly


discouraged as it makes the program logic
very complex.

The use of goto makes tracing the flow of the


program very difficult.

The use of goto makes the task of analyzing


and verifying the correctness of programs
(particularly those involving loops) very
difficult.

The use of goto can be simply avoided by


using break and continue statements.
Types of Storage Class in C

There are four types of storage classes in C,


1.Automatic storage class in C
2.Static storage class in C
3.Register storage class in C
4.External storage class in C
Auto(matic) Variable in C
All the local variables are automatic variables
by default. They are also known as auto
variables.

void main()
{
int x=10; //local variable (also automatic)
auto int y=20; //automatic variable
}
Static Variable in C
Static in C is a keyword to indicate a particular
memory location that remains occupied during the
program’s lifetime. In essence, defining something as
static makes it available throughout the entire
program, which is particularly useful when wanting to
keep values persistent between function calls.

Static variables enable data to remain after the


function has been executed and returned; this allows
the function to remember a value from a previous call,
making them both efficient and powerful.
How to use static keywords in C?
The static keyword can be used with both variables
and functions.

1. Static variable
Syntax

static data_type variable_name;

 Static Global Variable

When a C language’s global variable is declared with a


static keyword, it is known as a static global variable.

It is declared at the top of the program, and its


visibility is throughout the program.
Example
#include <stdio.h>
static char c;
static int i;
static float f;
static char s[100];
int main ()
{
printf("%c %d %f %s",c,i,f,s);
// the default values of c, i, f, and s will be printed.
return 0;
}

Output

blank 0 0.000000 (null)


Static Local Variable

It is a local variable, declared with a static


keyword. The memory of a static local variable
is valid throughout the program, but the scope
of visibility of a variable is the same as the
automatic local variables.

However, when the function modifies the static


local variable during the first function call, this
modified value will be available for the next
function call also.
Example
#include <stdio.h>
int main()
{
printf("%d",function());
printf("\n%d",function());
return 0;
}

int function()
{
static int count=0;
count++;
return count;
}
2. Static Function
It is a function declared with a static keyword.
Its lifetime is throughout the program. The static
function can be accessed within a file only.

Example :

#include<stdio.h>

static void function()


{
printf("Welcome to the CIMAGE COLLEGE");
}

int main() {
function();
return 0;
}
Extern Variable in C
External or global variables are declared using
the ‘extern’ keyword. You can declare an
external variable any number of times but, the
value can be assigned only once. Their default
value is 0 or null.

External variables specify an external linkage


and so such variables are not allocated any
memory.

The initialization must be done globally and not


within any function or block. If an external
variable is not initialized anywhere in the
program, the compiler will show an error.
Practice Questions
• Write a C program to calculate the perimeter and
area of a land
• Write a C program to swap the value of two
variables with the help of a third variable and without
the help of a third variable.
• Write a C program to find the large number among
two.
• Write a C program to find the large number among
three numbers.
• Write a C program to print even and odd numbers
from 1-50 using while, for and do-while loop.
• Write a C program to find the largest number
among ten numbers.
• Write a C program to print the Fibonacci series 1
1 2 3 5 8 13 21 upto 150 .
• Write a C program to reverse a 3-digit integer.
• Write a C program to find the prime number.
• Write a C program to prepare a bill for 10 books
after 20% discount for your library.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy