Unit 1 Introduction To C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

UNIT I

Introduction to C Programming: Overview of C; History and Features of C; Structure of a


C Program with Examples; Creating and Executing a C Program; Compilation process in C.C
Programming Basic Concepts: C Character Set; C tokens - keywords, identifiers, constants,
and variables; Data types; Declaration & initialization of variables; Symbolic constants. Input
and output with C: Formatted I/O functions - printf and scanf, control stings and escape
sequences, output specifications with printf functions; Unformatted I/O functions to read and
display single character and a string - getchar, putchar, gets and puts functions.

Introduction to C Programming
C is a High-Level Programming Language Used to Create High Level Program. It is a
General Purpose and Structured Programming. Developed By Dennis Ritchie at AT & T Bell
Laboratories In 1972 In USA. It Is also Called as Procedure Oriented Programming language.
It Is So Popular Language Because It Is Reliable, Simple and Easy to Use. C Language Is
Called "Compiled Languages" Since the Source Code Must First Be Compiled in Order to Run.

Why use C?
C was initially used for system development work, particularly the programs that make-
up the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language.
Some examples of the use of C might be −
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities

History of C
ALGOL (Algorithmic Language) 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.

PROF. NITIN D BELGAONKAR (JGI) 1


UNIT I

Features of C
Simple and Efficient
The C Language is a simple language that is easy to learn even for a beginner and is
super-efficient to use both in terms of the time of development and time of execution.

Portability
C Language program runs the same way everywhere. It means if you have written a
simple C program like a program to find sum of N numbers in C, on your Windows operating
system and then compiled it and run it, you can then take the compiled code and run it on any
other operating system or machine, like, Linux or macOS, etc., your C program will always
return the same result.

Structured Programming language


C language is a structured programming language because we can create functions in
the C language. Using functions we can separate a particular operation from the main program
and then use it again and again.

Powerful
It has a broad range of features like support for many data types, operators, keywords,
etc., that allows the structuring of code using functions, loops, decision-making statements, etc.
Then there are complex data structures like structures, arrays, etc., and pointers, which makes
C quite resourceful.

Rich Standard Library


C supports various inbuilt functions and libraries that create development fast.
The standard library support for the C language is superb and you will see that a lot of keywords
or ready-made operations that you will use while writing code in C language are already pre-
defined. You just have to use them, without worrying about how they work. These libraries are
called Header files in C language.

Syntax-based Language
There are proper rules for writing the code, and the C language strictly follows them.
If you write anything that is not allowed, you will get a compile-time error, which happens
when the compiler is unable to compile your code because of some incorrect code syntax.

Format Free Language


The C language is a format-free language. There are no line numbers needed in the C
language code, or we can say that the line number holds no significance. There is no need to
place statements on a specified location on a line.

Compiled Language
The C language uses a Compiler to compile the code into object code, which is nothing
but machine code that the computer understands. Hence to run a C language program we have
to install a C language compiler first.

PROF. NITIN D BELGAONKAR (JGI) 2


UNIT I

Structure of a C Program with Examples

1. Documentation section: The documentation section consists of a set of comment lines


giving the name of the program, the author and other details, which the programmer would
like to use later. /*multiline comments*/ or //single line comments

2. Link section: The link section provides instructions to the compiler to link functions from
the system library such as using the #include directive.

3. Definition section: The definition section defines all symbolic constants such using the
#define directive.

4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global declaration
section that is outside of all the functions. This section also declares all the user-defined
functions.

5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the executable part.
2. Executable part: There is at least one statement in the executable part. These two parts
must appear between the opening and closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function is the
logical end of the program. All statements in the declaration and executable part end with a
semicolon.

PROF. NITIN D BELGAONKAR (JGI) 3


UNIT I

6. Subprogram section: If the program is a multi-function program, then the subprogram


section contains all the user-defined functions that are called in the main () function. User-
defined functions are generally placed immediately after the main () function, although they
may appear in any order.

Creating and Executing a C Program


Step 1: Create a C program file using the gedit command on the terminal. gedit hello.c
Step 2: Create a C program by opening the hello.c file in the text editor.
Step 3: Compile the hello.c program file in the terminal with the gcc hello.c command.
Step 4: Using the ./a.out command, launch the hello executable file on the terminal.

Example
/*First c program*/
#include <stdio.h>
int main ()
{
printf ("welcome to c Programming language.\n");
return 0;
}
Output: welcome to c programming language.

Compilation process in C
Compilation process in C is converting an understandable human code into a Machine
understandable code and checking the syntax and semantics of the code to determine any
syntax errors or warnings present in our C program. Suppose we want to execute our C Program
written in an IDE (Integrated Development Environment). In that case, it has to go through
several phases of compilation (translation) to become an executable file that a machine can
understand.

Compilation process involves 4 steps

PROF. NITIN D BELGAONKAR (JGI) 4


UNIT I

The Preprocessor
The Preprocessor accepts source code as input and is responsible for
• removing comments
• Interpreting special preprocessor directives denoted by #. For example
• #include -- includes contents of a named file. Files usually called header files.
e.g #include <math.h> -- standard library maths file.
#include <stdio.h> -- standard library I/O file
• #define -- defines a symbolic name or constant. Macro substitution. #define
MAX_ARRAY_SIZE 100

C Compiler
The C compiler translates source to assembly code. The source code is received from
the preprocessor.

Assembler
The assembler creates object code. On a UNIX system you may see files with a .o
suffix (.OBJ on MSDOS) to indicate object code files.

Link Editor
If a source file references library functions or functions defined in other source files
the link editor combines these functions (with main()) to create an executable file.

C Programming Basic Concepts:


C Character Set
A character denotes any alphabet, digit or special symbol used to represent information.
Valid alphabets, numbers and special symbols allowed in C are
Alphabets a to z, A to Z
Numeric 0,1 to 9
Special Symbols { } [ ] ? - * / % ! ; , . _ # \ :
Escape Sequences
Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
The alphabets, numbers and special symbols when properly combined form constants,
variables and keywords.

PROF. NITIN D BELGAONKAR (JGI) 5


UNIT I

C tokens
• C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
• Each and every smallest individual unit in a C program is known as C tokens.
• C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: ―total‖, ―hello‖),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)

C keywords
There are certain words reserved for doing specific task, these words are known as
reserved word or keywords. These words are predefined and always written in lower case or
small letter. These keywords cann’t be used as a variable name as it assigned with fixed
meaning.
Some examples are int, short, signed, unsigned, default, volatile, float, long, double,
break, continue, typedef, static, do, for, union, return, while, do, extern, register, enum, case,
goto, struct, char, auto, const etc.

Identifiers
Identifiers are user defined word used to name of entities like variables, arrays,
functions, structures etc. Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and lower case), digits and underscore
(_) sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case considered differently, for example
code, Code, CODE etc. are different identifiers.
5) identifiers are generally given in some meaningful name such as value, net_salary, age, data
etc. An identifier name may be long, some implementation recognizes only first eight
characters, most recognize 31 characters. ANSI standard compiler recognize 31 characters.
Some invalid identifiers are 5cb, int, res#, avg no etc.

Constants
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
CONSTANT EXAMPLE
Decimal Constant 10, 20, 450 etc.
Real or Floating-point Constant 10.3, 20.2, 450.0 etc.
Octal Constant 021, 033, 046 etc.
Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.
Character Constant ‘a’, ‘b’, ‘x’, etc.
String Constant “C”, “C program” etc.

PROF. NITIN D BELGAONKAR (JGI) 6


UNIT I

2 ways to define constant in C


There are two 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.
const float PI=3.14;
Now, the value of PI variable can’t be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf(“The value of PI is: %f”,PI);
return 0;
}
Output
The value of PI is: 3.140000

2) C #define preprocessor
The #define preprocessor is also used to define constant.
Syntax:
#define token value

Example
#include<stdio.h>
#define PI 3.14
int main()
{
printf(“The value of PI is: %f”,PI);
return 0;
}
Output
The value of PI is: 3.140000

Data types
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Data types refer to an extensive system used for declaring variables or functions of different
types before its use. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted. The value of a variable can be changed any time.
C has the following 4 types of data types
• basic built-in data types: int, float, double, char
• Enumeration data type: enum
• Derived data type: pointer, array, structure, union
• Void data type: void

PROF. NITIN D BELGAONKAR (JGI) 7


UNIT I

Integer Data Type


The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can be stored in int data type in C.
• Range: -2,147,483,648 to 2,147,483,647
• Size: 4 bytes
• Format Specifier: %d

The integer data type can also be used as


• unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
• short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768
to 32,767.
• long int: Larger version of the int datatype so can store values greater than int.
• unsigned short int: Similar in relationship with short int as unsigned int with int.

Float Data Type


In C programming float data type is used to store floating-point values. Float in C is
used to store decimal and exponential values. It is used to store decimal numbers (numbers
with floating point values) with single precision.
• Range: 1.2E-38 to 3.4E+38
• Size: 4 bytes
• Format Specifier: %f

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as compared to
that float then it is much more obvious that it occupies twice the memory occupied by the
floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal
point.
• Range: 1.7E-308 to 1.7E+308
• Size: 8 bytes
• Format Specifier: %lf

Character Data Type


Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
• Range: (-128 to 127) or (0 to 255)
• Size: 1 byte
• Format Specifier: %c

PROF. NITIN D BELGAONKAR (JGI) 8


UNIT I

Void Data Type


The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent nothing. Void
is used in multiple ways as function return type, function arguments as void, and pointers to
void.

Below is a list of ranges along with the memory requirement and format specifiers on the 32-
bit GCC compiler.
Data Type Size Range Format
(bytes) Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long 8 0 to %llu


int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

There are two types of type qualifier in c


Size qualifier: short, long
Sign qualifier: signed, unsigned
When the qualifier unsigned is used the number is always positive, and when signed is
used number may be positive or negative. If the sign qualifier is not mentioned, then by default
sign qualifier is assumed. The range of values for signed data types is less than that of unsigned
data type. Because in signed type, the left most bit is used to represent sign, while in unsigned
type this bit is also used to represent the value.

PROF. NITIN D BELGAONKAR (JGI) 9


UNIT I

Symbolic constant
Symbolic constant is a name that substitute for a sequence of characters and,
characters may be numeric, character or string constant. These constant are generally defined
at the beginning of the program as #define name value , here name generally written in upper
case for example
#define MAX 10
#define CH ‘b’
#define NAME “sony”

Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.

Rules for naming variables are:


• The name of a variable can be composed of letters, digits, and the underscore character.
• It must begin with either a letter or an underscore.
• Upper and lowercase letters are distinct because C is case-sensitive.

Declaration & initialization of variables


Declaring a variable:
Declaration of variables specify its name, data types and range of the value that
variables can store depends upon its data types.
Syntax:
data type variable_list;

Example
int a;
float b;

Variable initialization:
When we assign any initial value to variable during the declaration, is called initialization of
variables. When variable is declared but contain undefined value then it is called garbage value.
The variable is initialized with the assignment operator such as
data type variable name=value;
Example: int a=20;

Format Specifiers
• To print values of different data types using the printf() statement and while taking input
using the scanf() function, it is mandatory to use format specifiers.
• It is a way to tell the compiler what type of data is in a variable.
• Some examples are %c, %d, %f, etc.

Here is a list of all the format specifiers.

PROF. NITIN D BELGAONKAR (JGI) 10


UNIT I

Data Type Format Specifier

short int %hd

unsigned short int %hu

unsigned int %u

int %d

long int %ld

unsigned long int %lu

long long int %lld

unsigned long long int %llu

signed char %c

unsigned char %c

float %f

double %lf

long double %Lf

Input and output functions in c:


C input and output functions are divided into Formatted and Unformatted Input/Output
functions.

Formatted Input/Output functions


Formatted I/O refers to input and output that has been arranged in a particular format.
These functions are called formatted I/O functions as they can use format specifiers in these
functions. Moreover, we can format these functions according to our needs.

The following formatted I/O functions will be discussed in this section-


• printf()
• scanf()

1. printf():
In C, printf() is a built-in function used to display values like numbers, characters, and
strings on the console screen. It’s pre-defined in the stdio.h header, allowing easy output
formatting in C programs.

PROF. NITIN D BELGAONKAR (JGI) 11


UNIT I

Syntax 1
printf(“Format Specifier”, var1, var2, …., varn);

Example
// C program to implement
// printf() function
#include <stdio.h>
int main()
{
// Declaring an int type variable
int a;

// Assigning a value in a variable


a = 20;

// Printing the value of a variable


printf("%d", a);

return 0;
}
Output
20

Syntax 2:
printf(“Enter the text which you want to display”);

Example
// C program to implement
// printf() function
#include <stdio.h>
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}

Output
This is a string

2. scanf():
In C, scanf() is a built-in function for reading user input from the keyboard. It can read
values of various data types like integers, floats, characters, and strings. scanf() is a pre-defined
function declared in the stdio.h header file. It uses the & (address-of operator) to store user
input in the memory location of a variable.

PROF. NITIN D BELGAONKAR (JGI) 12


UNIT I

Syntax
scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example
// C program to implement
// scanf() function
#include <stdio.h>
int main()
{
int num1;

// Printing a message on the output screen


printf("Enter a integer number: ");

// Taking an integer value from keyboard


scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);

return 0;
}

Output
Enter a integer number: 56
You have entered 56

Unformatted Input/Output functions


These functions are used exclusively for character data types or character arrays/strings.
They are designed for reading single inputs from the user at the console and for displaying
values on the console.

Why “Unformatted”?:
They are referred to as “unformatted” I/O functions because they do not support format
specifiers. Unlike formatted I/O functions like printf() and scanf(), you cannot use format
specifiers to control the formatting of the data. They display or read data as-is without
formatting options.

The following are unformatted I/O functions


• getch()
• getche()
• getchar()
• putchar()
• gets()
• puts()

PROF. NITIN D BELGAONKAR (JGI) 13


UNIT I

• putch()
• getch():

1. getch():
In C, getch() reads a single character from the keyboard without displaying it on the
screen. It immediately returns without requiring the user to press the Enter key. This function
is declared in the conio.h header file and is often used for controlling screen display.

Syntax
getch();
or
variable-name = getch();

Example
// C program to implement getch() function
#include <conio.h>
#include <stdio.h>
int main()
{
printf("Enter any character: ");

// Reads a character but not displays


getch();
return 0;
}
Output
Enter any character:

2. getche():
In C, getche() reads a single character from the keyboard, displays it on the screen, and
immediately returns without requiring the user to press the Enter key. This function is declared
in the conio.h header file.

Syntax
getche();
or
variable_name = getche();

Example
// C program to implement the getche() function
#include <conio.h>
#include <stdio.h>
int main()
{
printf("Enter any character: ");

PROF. NITIN D BELGAONKAR (JGI) 14


UNIT I

// Reads a character and displays immediately


getche();
return 0;
}
Output
Enter any character: g

3. getchar():
In C, getchar() reads a single character from the keyboard and waits until the Enter key
is pressed. It processes one character at a time. This function is declared in the stdio.h header
file

Syntax
Variable-name = getchar();

Example
// C program to implement the getchar() function
#include <conio.h>
#include <stdio.h>
int main()
{
// Declaring a char type variable
char ch;
printf("Enter the character: ");

// Taking a character from keyboard


ch = getchar();
// Displays the value of ch
printf("%c", ch);
return 0;
}

Output
Enter the character: a
a

4. putchar():
In C, putchar() is used to display a single character at a time, either by passing the
character directly or by using a variable that stores the character. This function is declared in
the stdio.h header file.

Syntax
putchar(variable_name);

Example
// C program to implement the putchar() function

PROF. NITIN D BELGAONKAR (JGI) 15


UNIT I

#include <conio.h>
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
// Displays that character
putchar(ch);
return 0;
}

Output
Enter any character: Z
Z

5. gets():
In C, gets() reads a group of characters or strings from the keyboard, and these
characters are stored in a character array. It allows you to input space-separated texts or strings.
This function is declared in the stdio.h header file.

Syntax
char str[length of string in number]; //Declare a char type variable of any length

gets(str);

Example
// C program to implement the gets() function
#include <conio.h>
#include <stdio.h>
int main()
{
// Declaring a char type array of length 50 characters
char name[50];

printf("Please enter some texts: ");

// Reading a line of character or a string


gets(name);

// Displaying this line of character


// or a string
printf("You have entered: %s",
name);
return 0;

PROF. NITIN D BELGAONKAR (JGI) 16


UNIT I

}
Output
Please enter some texts: jgi bca
You have entered: jgi bca

6. puts():
In C programming, puts() is used to display a group of characters or strings that are
already stored in a character array. This function is declared in the stdio.h header file.

Syntax
puts(identifier_name );

Example
// C program to implement the puts() function
#include <stdio.h>
int main()
{
char name[50];
printf("Enter your text: ");

// Reads string from user


gets(name);
printf("Your text is: ");

// Displays string
puts(name);
return 0;
}

Output
Enter your text: jgi bca
Your text is: jgi bca

7. putch():
In C, putch() is used to display a single character provided by the user, and it prints the
character at the current cursor location. This function is declared in the conio.h header file

Syntax
putch(variable_name);

Example
// C program to implement the putch() functions
#include <conio.h>
#include <stdio.h>
int main()
{

PROF. NITIN D BELGAONKAR (JGI) 17


UNIT I

char ch;
printf("Enter any character:\n ");

// Reads a character from the keyboard


ch = getch();

printf("\nEntered character is: ");

// Displays that character on the console


putch(ch);
return 0;
}

Output
Enter any character:
Entered character is: d

Formatted I/O vs Unformatted I/O

S No. Formatted I/O functions Unformatted I/O functions

These Formatted I/O functions will Whereas, Unformatted I/O functions


1 provide input or display output in the won’t allow to take input or display output
user’s desired format. in user desired format.

2 They will support format specifiers. They will support not format specifiers.

These functions are not more user-


3 These will store data more user-friendly
friendly.

In Formatted I/0 Functions, we can use Here we can use only character and string
4
all data types. data types

Example-getch(), getche(), gets() and


5 Examples -printf(), scanf
puts()

PROF. NITIN D BELGAONKAR (JGI) 18

You might also like