0% found this document useful (0 votes)
23 views53 pages

Unit1 PC

Uploaded by

sy312916
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views53 pages

Unit1 PC

Uploaded by

sy312916
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

MUST DO TOPICS

Unit-1
• Features of C
• Compilation process
• Algorithm and Flowchart
• Pseudocodes
• Datatypes
• Keywords and Identifiers
• Operators (Increment, Decrement and Bitwise operators)
• Type conversion in expressions
C Programming Language

C language Tutorial with programming approach for beginners and professionals, helps you to
understand the C language tutorial easily. Our C tutorial explains each topic with programs.

The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

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

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language

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

It provides the core concepts like the array, strings, functions, file handling, etc. that are being
used in many languages like C++, Java, C#, etc.

2) C as a 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.

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

C is a procedural language. In C, variables and function prototypes must be declared before


being used.
4) C as a structured programming language

A structured programming language is a subset of the procedural language. Structure means


to break a program into parts or blocks so that it may be easy to understand.

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

5) C as a mid-level programming language

C is considered as a middle-level language because it supports the feature of both low-level


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

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


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

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

C Program

In this tutorial, all C programs are given with C compiler so that you can quickly change the C
program code.

File: main.c

1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of
the c language.

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.

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


Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.

Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple
C is 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 is intended 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.


First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the
first c program.

To write the first c program, open the C console and write the following code:

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

#include <stdio.h> includes the standard input output library functions. The printf() function
is defined in stdio.h . int main() The main() function is the entry point of every program in
c language. printf() The printf() function is used to print data on the console.

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

How to compile and run the c program

There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


Compilation process in c

What is a compilation?

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

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.

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

o
Preprocessor o
Compiler o
Assembler o
Linker
Preprocessor: The source code is the code which is written in a text editor and the source code
file is given an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed to the
compiler.

Compiler: The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler converts
the pre-processed code into assembly code.

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

Linker: Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension.
The main working of the linker is to combine the object code of library files with the object
code of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the object
code of our program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the source file but
differs only in their extensions. In DOS, the extension of the executable file is '.exe', and in
UNIX, the executable file can be named as 'a.out'. For example, if we are using printf() function
in a program, then the linker adds its associated code in an output file.

Let's understand through an example.

hello.c

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }

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


In the above flow diagram, the following steps are taken to execute a program:
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded
source code would be hello.i. o The expanded source code is passed to the compiler,
and the compiler converts this expanded source code into assembly code. The extension
of the assembly code would be hello.s. o This assembly code is then sent to the
assembler, which converts the assembly code into object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.

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.

Variables in C

A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring the variable is given below:

1. a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';
Rules for defining variables o A variable can have alphabets, digits, and underscore. o A
variable name can start with the alphabet, and underscore only. It can't start with a digit. o
No whitespace is allowed within the variable name. o A variable name must not be any
reserved word or keyword, e.g. int, float, etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 2;
2. int a b;
3. int long;

Types of Variables in C

There are many types of variables in c:

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

Local Variable

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

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

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

Global Variable

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

It must be declared at the start of the block.


1. int value=20;//global variable
2. void function1(){
3. int x=10;//local variable
4. }

Static Variable

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

It retains its value between multiple function calls.

1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }

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

Automatic Variable

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

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }

External Variable

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

myfile.h

1. extern int x=10;//external variable (also global) program1.c


1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Data Types in C

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

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range


char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295


float 4 byte

double 8 byte

long double 10 byte

Int:

Integers are entire numbers without any fractional or decimal parts, and the int data type is
used to represent them.

It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive
and negative numbers because it is signed by default.

An int takes up 4 bytes of memory on most devices, allowing it to store values between around
-2 billion and +2 billion.

Char:

Individual characters are represented by the char data type. Typically used to hold ASCII or
UTF-8 encoding scheme characters, such as letters, numbers, symbols, or commas. There are
256 characters that can be represented by a single char, which takes up one byte of memory.
Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.

Float:

To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.

The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4
x 1038 in 4 bytes of memory.

Double:

Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places,
yields larger values. C treats floating point numbers as doubles by default if no explicit type is
supplied.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables
for the number pi.

Derived Data Type

Beyond the fundamental data types, C also supports derived data types, including arrays,
pointers, structures, and unions. These data types give programmers the ability to handle
heterogeneous data, directly modify memory, and build complicated data structures.

Array:

An array, a derived data type, lets you store a sequence of fixed-size elements of the same
type. It provides a mechanism for joining multiple targets of the same data under the same
name.

The index is used to access the elements of the array, with a 0 index for the first entry. The size
of the array is fixed at declaration time and cannot be changed during program execution. The
array components are placed in adjacent memory regions.

Here is an example of declaring and utilizing an array:

1. #include <stdio.h> 2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10; 8. numbers[1] = 20; 9.
numbers[2] = 30;
10. numbers[3] = 40;
11. numbers[4] = 50; 12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }

Output:
Values in the array: 10 20 30 40 50
Pointer:

A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by specifying
the memory address of the variable. Pointers are commonly used in tasks such as function
pointers, data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:

1. #include <stdio.h> 2.
3. int main() {
4. int num = 42; // An integer variable
5. int *ptr; // Declares a pointer to an integer
6.
7. ptr = # // Assigns the address of 'num' to the pointer
8.
9. // Accessing the value of 'num' using the pointer
10. printf("Value of num: %d\n", *ptr); 11.
12. return 0;
13. }

Output:

Value of num: 42
Structure:

A structure is a derived data type that enables the creation of composite data types by allowing
the grouping of many data types under a single name. It gives you the ability to create your
own unique data structures by fusing together variables of various sorts.

1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:

1. #include <stdio.h>
2. #include <string.h>
3. // Define a structure representing a person
4. struct Person {
5. char name[50];
6. int age;
7. float height; 8. };
9.
10. int main() {
11. // Declare a variable of type struct Person
12. struct Person person1; 13.
14. // Assign values to the structure members
15. strcpy(person1.name, "John Doe");
16. person1.age = 30; 17. person1.height = 1.8; 18.
19. // Accessing the structure members
20. printf("Name: %s\n", person1.name);
21. printf("Age: %d\n", person1.age); 22. printf("Height: %.2f\n",
person1.height); 23.
24. return 0;
25. }

Output:

Name: John Doe


Age: 30
Height: 1.80
Union:

A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members
of a union all share a single memory space. A value can only be held by one member of a union
at any given moment. When you need to represent many data types interchangeably, unions
come in handy. Like structures, you can access the members of a union by using the dot (.)
operator.

Here is an example of a union being declared and used:

1. #include <stdio.h>
2. // Define a union representing a numeric value
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
9. // Declare a variable of type union NumericValue
10. union NumericValue value;
11. // Assign a value to the union
12. value.intValue = 42;
13. // Accessing the union members
14. printf("Integer Value: %d\n", value.intValue);
15. // Assigning a different value to the union
16. value.floatValue = 3.14;
17. // Accessing the union members
18. printf("Float Value: %.2f\n", value.floatValue); 19.
20. return 0;
21. }

Output:

Integer Value: 42
Float Value: 3.14
Enumeration Data Type

A set of named constants or enumerators that represent a collection of connected values can
be defined in C using the enumeration data type (enum). Enumerations give you the means
to give names that make sense to a group of integral values, which makes your code easier to
read and maintain.

Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h> 2.
3. // Define an enumeration for days of the week
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday 12. };
13.
14. int main() {
15. // Declare a variable of type enum DaysOfWeek
16. enum DaysOfWeek today;
17.
18. // Assign a value from the enumeration
19. today = Wednesday;
20.
21. // Accessing the enumeration value
22. printf("Today is %d\n", today); 23.
24. return 0;
25. }

Output:

Today is 2
Void Data Type
The void data type in the C language is used to denote the lack of a particular type. Function
return types, function parameters, and pointers are three situations where it is frequently
utilized.

Function Return Type:

A void return type function does not produce a value. A void function executes a task or action
and ends rather than returning a value.

Example:

1. void printHello() { printf("Hello, world!\n"); } Function

Parameters:

The parameter void can be used to indicate that a function accepts no arguments.

Example:

1. void processInput(void) { /* Function logic */ } Pointers:

Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a
method for working with pointers to ambiguous or atypical types.

Example:

1. void* dataPtr;

The void data type is helpful for defining functions that don't accept any arguments when
working with generic pointers or when you wish to signal that a function doesn't return a value.
It is significant to note that while void* can be used to build generic pointers, void itself cannot
be declared as a variable type.

Here is a sample of code that shows how to utilize void in various situations:

1. #include <stdio.h>
2. // Function with void return type
3. void printHello() {
4. printf("Hello, world!\n");
5. }
6. // Function with void parameter
7. void processInput(void) {
8. printf("Processing input...\n");
9. }
10.
11. int main() {
12. // Calling a void function 13. printHello();
14.
15. // Calling a function with void parameter
16. processInput(); 17.
18. // Using a void pointer
19. int number = 10;
20. void* dataPtr = &number;
21. printf("Value of number: %d\n", *(int*)dataPtr); 22.
23. return 0;
24. }

Output:

Hello, world!
Processing input...
Value of number: 10

Keywords in C

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

A list of 32 keywords in the c language is given below:


auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while


C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore. If the identifier is not used in the external linkage, then it is called as an internal
identifier. If the identifier is used in the external linkage, then it is called as an external
identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with
an alphabetical character or an underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52
alphabetical characters (uppercase and lowercase), underscore character, and ten numerical
digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that
represent the identifiers.
Rules for constructing C identifiers o The first character of an identifier should be either an
alphabet or an underscore, and then it can be followed by any of the character, digit, or
underscore.
o It should not begin with any numerical digit. o In identifiers, both uppercase and
lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier. o The length of the identifiers should
not be more than 31 characters. o Identifiers should be written in such a way that it is
meaningful, short, and easy to read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1. 2sum (starts with a numerical digit)


2. int (reserved word)
3. char (reserved word)
4. m+n (special character, i.e., '+')

Types of identifiers o
Internal
identifier o
External
identifier

Internal Identifier

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

External Identifier

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

Differences between Keyword and Identifier

Keyword Identifier

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


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

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

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


characters.

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

Let's understand through an example.

1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }

Output

Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore,
we conclude that the identifiers are case sensitive.

C Operators

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

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

o Arithmetic Operators
o Relational Operators o Shift Operators o
Logical Operators o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator o Misc Operator
Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right


Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C Format Specifier

The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a '%'
character.

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


Description
Format
specifier

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

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

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

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

%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints the 6
values after '.'.

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

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

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

%c It is used to print the unsigned character.

%s It is used to print the strings.

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

Let's understand the format specifiers in detail through an example.

o %d

1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b); 6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }

In the above code, we are printing the integer value of b and c by using the %d specifier.

Output
o %u

1. int main()
2. {
3. int b=10;
4. int c= -10;
5. printf("Value of b is:%u", b); 6. printf("\nValue of c is:%u",c);
7.
8. return 0;
9. }

In the above program, we are displaying the value of b and c by using an unsigned format
specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it
does not print the value of c as c contains the negative value. Output

o %o

1. int main()
2. {
3. int a=0100;
4. printf("Octal value of a is: %o", a);
5. printf("\nInteger value of a is: %d",a);
6. return 0;
7. }
In the above code, we are displaying the octal value and integer value of a. Output

o %x and %X

1. int main()
2. {
3. int y=0xA;
4. printf("Hexadecimal value of y is: %x", y);
5. printf("\nHexadecimal value of y is: %X",y);
6. printf("\nInteger value of y is: %d",y);
7. return 0;
8. }

In the above code, y contains the hexadecimal value 'A'. We display the hexadecimal value of
y in two formats. We use %x and %X to print the hexadecimal value where %x displays the
value in small letters, i.e., 'a' and %X displays the value in a capital letter, i.e., 'A'.

Output
o

1. main()
2. 3.
4.
5.
%f

int { float
y=3.4;
printf("Floating point value of y is: %f", y); return
0;
6. }

The above code prints the floating value of y.

Output

o %e

1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %e", y);
5. return 0;
6. }

Output
o

1. main()
2. 3.
4.
5.

%E

int {
float y=3;
printf("Exponential value of y is: %E", y); return
0;
6. }

Output

o %g

1. int main()
2. {
3. float y=3.8;
4. printf("Float value of y is: %g", y);
5. return 0;
6. }
o

1. main()
2. 3.
4.
5.
In the above code, we are displaying the floating value of y by using %g specifier. The %g
specifier displays the output same as the input with a same precision. Output

%p

int {
int y=5;
printf("Address value of y in hexadecimal form is: %p", &y); return
0;
6. }

Output

o %c

1. int main()
2. {
3. char a='c';
o

1. main()
2. 3.
4.
5.
4. printf("Value of a is: %c", a);
5. return 0;
6. }

Output

o %s

int main()
1. {
2. printf("%s", "javaTpoint");
3. return 0;
4. }

Output:
o

1. main()
2. 3.
4.
5.

Minimum Field Width Specifier

Suppose we want to display an output that occupies a minimum number of spaces


on the screen. You can achieve this by displaying an integer number after the
percent sign of the format specifier.

1. int main()
2. {
3. int x=900;
4. printf("%8d", x);
5. printf("\n%-8d",x);
6. return 0;
7. }

In the above program, %8d specifier displays the value after 8 spaces while %-8d
specifier will make a value left-aligned.

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

1. int main()
2. {
3. int x=12;
4. printf("%08d", x);
5. return 0;
6. }

In the above program, %08d means that the empty space is filled with zeroes. Output

Specifying Precision

We can specify the precision by using '.' (Dot) operator which is followed by integer and format specifier.

1. int main()
2. {
3. float x=12.2;
4. printf("%.2f", x);
5. return 0;
6. }
Output:
Constants in C

In programming languages like C, constants are essential because they give you a mechanism
to store unchanging values that hold true throughout the course of the program. These numbers
may be used for several things, such as creating mathematical constants or giving variables
set values. We will discuss the idea of constants in C, their syntax, how to declare and use
them and give illustrated examples along with their anticipated results in this blog article. By
the end of this article, you'll have a firm grasp of constants and their importance in C
programming.

A constant in C is a value that doesn't change as the program runs. Integers, floating-point
numbers, characters, and strings are just a few of the several types of constants that may be
employed. When a constant has a value, it cannot be changed, unlike variables. They may be
utilized in various operations and computations and serve as the program's representation of
fixed values.

Advantages of C Constants:

There are several advantages of C Constants. Some main advantages of C Constants are as follows:

1. Programmers may use constants to provide names that have meaning to fixed numbers,
which makes the code simpler to comprehend and update.
2. Constants assist in avoiding the usage of magic numbers, which are hard-coded values,
in the code. Instead, constants offer named representations of such values, enhancing
the code's readability.
3. Constants are reusable throughout the program, allowing for constant values in various
locations and lowering the possibility of errors brought on by typos or inconsistent
values.
4. Calculations or processes inside the program can be optimized by using certain
constants, such as mathematical or physical constants.
5. A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming", etc.
There are different types of constants in C programming.
List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

2 ways to define constant in C


There are to ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword

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

1. const float PI=3.14;

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

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

Output:

The value of PI is: 3.140000


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

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }

Output:

Compile Time Error: Cannot modify a const object


2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive.

Types of constant:

There are different types of Constants in C. Some of them are as follows:

Decimal Constant

A whole number represented in base 10 is known as a decimal constant. It has digits that range
from 0 to 9. Declaring a decimal constant has a simple syntax that just requires the value to be
written.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. int decimal = 42;
5. printf("The decimal constant is: %d\n", decimal);
6. return 0;
7. }

Output:

The decimal constant is: 42


Real or Floating-Point Constant:

A fractional component or exponentiation of a number is represented by a real or


floatingpoint constant. It can be expressed with a decimal point, the letter "E", or the symbol
"e" in exponential or decimal notation.
Example:

1. #include <stdio.h>
2.
3. int main() {
4. float real = 3.14;
5. printf("The real constant is: %f\n", real);
6. return 0;
7. }

Output:

The real constant is: 3.140000


Octal Constant:

A base 8 value is represented by an octal constant. It is prefixed with a '0' (zero) to show that it
is an octal constant and has digits ranging from 0 to 7.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. int octal = 052; // Octal representation of decimal 42
5. printf("The octal constant is: %o\n", octal);
6. return 0;
7. }

Output:

The octal constant is: 52


Hexadecimal Constant:

A base-16 value is represented by a hexadecimal constant. It uses letters A to F (or a to f) and


numbers 0 to 9 to represent values from 10 to 15. It is prefixed with '0x' or '0X' to identify it
as a hexadecimal constant.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42
5. printf("The hexadecimal constant is: %x\n", hexadecimal);
6. return 0;
7. }
Output:

The hexadecimal constant is: 2a


Character Constant

A character constant represents a single character that is enclosed in single quotes.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. char character = 'A';
5. printf("The character constant is: %c\n", character);
6. return 0;
7. }

Output:

The character constant is: A


String Constant:

A series of characters wrapped in double quotes is represented by a string constant. It is a character


array that ends with the null character \0.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. char string[] = "Hello, World!";
5. printf("The string constant is: %s\n", string);
6. return 0;
7. }

Output:

The string constant is: Hello, World!


Rules for constructing constants:

The creation of constants must follow specified guidelines. These guidelines specify the format
that constants of various kinds must follow in order for the compiler to accept them as
legitimate. The guidelines for creating constants in C are as follows:

Integer Constants:
1. The digits of an integer constant can range from 0 to 9.
2. A decimal point should not be present in an integer constant.
3. Positive or negative integer constants are also possible.
4. You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for
unsigned, 'L' or 'l' for long, or 'LL' or 'll' for long long.

Floating-Point Constants:
1. A decimal point, an exponent, or digits can all be found in floating-point constants.
2. Either exponential notation or decimal notation can be used to write them.
3. 'E' or 'e' can be used to denote an exponent.
4. You can add a suffix to a constant's name to define its type. For instance, "F" or "f"
stands for float and "L" or "l" for long double.

Octagonal Constants
1. Base 8 is used for writing octal constants.
2. They are made up of the numerals 0 through 7.
3. A '0' (zero) should come before any octal constants.

Hexadecimal Constants:
1. Constants in hexadecimal are expressed in base 16.
2. To represent numbers from 10 to 15, they are made up of numerals 0 to 9 and letters A
to F (or a to f).
3. Prefixing a hexadecimal constant with '0x' or '0X' is appropriate.

Character Constants:
1. Individual characters are represented as character constants when they are in single
quotes.
2. A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be
used as these characters.

String Constants:
1. A series of characters surrounded in double quotes is represented by string constants.
2. They are essentially character arrays that are closed with the null character "0".

Conclusion:

As a result of their representation of fixed values that don't change during the course of the
program, constants are crucial in C programming. By following the rules for making constants,
programmers may create reliable and practical representations of data in their programs.

By giving descriptive names to fixed values, minimizing the usage of "magic numbers", and
encouraging self-documenting code, constants improve the readability of code. By offering a
central area to edit constant values, facilitating simple modifications, and lowering the
possibility of mistakes, they also aid in the maintainability of the code.
As constants may be used and referenced several times throughout the program, using them in
C programs also increases code reuse. When utilizing the same value again, it assures
consistency and lessens the possibility of adding errors or mistakes.

Constants can also improve computations and processes, particularly when physical or
mathematical constants are involved. Programmers can create code that is more effective and
optimized by utilizing constants rather than hard-coding variables.

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

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

o Keywords in C o Identifiers in C o Strings in C o Operators in C o


Constant in C o Special Characters in C

Let's understand each token one by one.

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:

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C
are the user-defined words. It can be composed of uppercase letters, lowercase letters,

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

Strings in C

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

Now, we describe the strings in different ways:

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

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

{'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.


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
o Relational Operators
o Shift Operators o
Logical Operators o
Bitwise Operators o
Conditional
Operators o
Assignment Operator
o 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.

Types of constants in C

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used for
another purpose.
There are two ways of declaring constant:

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.

o Using const keyword


o Using #define pre-processor
o 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.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing
the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory. o Period (.): It is used to
access a member of a structure or a union.

Programming Errors in C

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

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

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

o Syntax error o
Run-time
error o Linker
error

o Logical error o
Semantic error
Syntax error

Syntax errors are also known as the compilation errors as they occurred at the compilation time,
or we can say that the syntax errors are thrown by the compilers. These errors are mainly
occurred due to the mistakes while typing or do not follow the syntax of the specified
programming language. These mistakes are generally made by beginners only because they are
new to the language. These errors can be easily debugged or corrected.

For example:

1. If we want to declare the variable of type integer,


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

Commonly occurred syntax errors are:

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


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

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
In the above output, we observe that the code throws the error that 'a' is undeclared. This error is
nothing but the syntax error only.

There can be another possibility in which the syntax error can exist, i.e., if we make mistakes in
the basic construct. Let's understand this scenario through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }

In the above code, we put the (.) instead of condition in 'if', so this generates the syntax error as
shown in the below screenshot.

Output

Run-time error

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

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

Output

In the above output, we observe that the code shows the run-time error, i.e., division by zero.

Linker error

Linker errors are mainly generated when the executable file of the program is not created. This
can be happened either due to the wrong function prototyping or usage of the wrong header
file. For example, the main.c file contains the sub() function whose declaration and definition
is done in some other file such as func.c. During the compilation, the compiler finds the sub()
function in func.c file, so it generates two object files, i.e., main.o and func.o. At the execution
time, if the definition of sub() function is not found in the func.o file, then the linker error will
be thrown. The most common linker error that occurs is that we use Main() instead of main().

Let's understand through a simple example.

1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
Logical error

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

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop 7. {
8. sum=sum+k;
9. k++;
10. }
11. printf("The value of sum is %d", sum);
12. return 0;
13. }

Output

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

Semantic error

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

The following can be the cases for the semantic error:


Let's understand through an example.

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

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

Output
MUST DO QUESTIONS
UNIT-1
2-3 marks

➢ C Character set

➢ Identifier

➢ Keyword

➢ Tokens

➢ Constant (and its types)

➢ Declaration

➢ Statement

➢ Comments

➢ Expression statement

➢ Sizeof operator

➢ Whitespaces

➢ Typedef

➢ Enumeration

➢ Ternary/Conditional operator

➢ Comma Operator

➢ Escape sequences

➢ Unary operator
(Increment and decrement)

➢ Break statement

➢ Goto statement
➢ Continue statement
Differentiation

➢ printf() vs scanf()
➢ Lvalue Vs Rvalue

➢ = and ==

➢ While Vs do while

➢ Identifier Vs Variable

➢ Entry Controlled loop Vs Exit controlled loop

➢ Pre Vs post increment

➢ Pre Vs post decrement

➢ Getch() Vs getche()

5-10marks

➢ What is C? Briefly explain its history along with its features. What are its limitations?

➢ What are various types of errors?

➢ Explain various data types in detail.

➢ Explain various operators in detail. What is the hierarchy/precedence of operators?

➢ What is Type conversion? What are its types? Explain with the help of example.

➢ What is decision control instructions/decision making statements/Branching statements?


Explain its types with syntax and example.

➢ What are loops? Explain its types with syntax and example.

➢ Explain switch case/Decision using switch case with syntax and code. How is it different
from multiple else if statement?

➢ Briefly explain all format codes (like %d, %f etc).

You might also like