0% found this document useful (0 votes)
0 views42 pages

C Programming Notes

Uploaded by

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

C Programming Notes

Uploaded by

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

C Programming Notes

 The base or father of programming languages is 'ALGOL.' It was first introduced in


1960. 'ALGOL' introduced the concept of structured programming to the developer
community.
 The C programming language was developed at Bell Laboratories in 1972 by
Dennis Ritchie.

Why did they name the language as ‘C’?


Many of C programming Language’s principles and ideas were derived from the “B”
Language, which was the language used earlier to the release of this.
That’s why they named this newly developed language as “C”

What is C Language?
C is a general purpose, machine dependent, procedural, structured, middle-level
programming language.
It was mainly developed as a system programming language to write an operating
system

Why to learn C Language?


Point 1:
C is the base language for a lot of other programming languages that came into
existence after this.

Point 2:
Learning C helps us to understand the underlying architecture of how things work.

Point 3:
C programming language has fewer libraries in comparison with other high-level
languages. You will not be dependent on the programming language entirely for
implementing some basic operations and implementing them on your own will also help
you to build your analytical skills.

Point 4:
C is extensively used in Embedded Programming.
Where do we use C Language?
Few examples of C being used –

 Database systems
 Graphics packages
 Word processors / Text Editors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters
 Simulators

Key Features of C programming Language


1. General Purpose Programming Language.
2. Structured (or) Procedural (or) Modular Programming Language.
3. C is a Middle Level Programming Language
4. Variety of Data Types and powerful Operators
5. Standard Libraries – with built-in functions
6. Efficient Language – Programmers can fine-tune their code for the most efficient
use of memory
7. Speed - The compilation and execution of a C Program are much faster when
compared with even the present-day modern programming language.

IDEs – Integrated Development Environment is a software that acts as a programmer’s


simulator.
Some Popular IDEs used for developing C programs:
Turbo C
DevC++
Code::Blocks
Visual Studio Code
Eclipse
NetBeans
Sublime Text

Compilers
A compiler is a special program that processes statements written in a particular
programming language and turns them into machine language or "code" that a
computer's processor uses.

Source Code Compiles Object Code


filename.c (Machine
Language)

Output Run

In simple words we can say that a compiler is a “Translator”

Steps -
 1st: It reads the Program
 2nd: Checks for any Syntax errors, if any reverts a consolidated list of all the errors
encountered within the program to the programmer.
 3rd: If the program does not have any errors, it is then converted into the Object Code.

Source Code
FileName: test.c

#include<stdio.h>
int main() Compiler
{
printf("Hello");
return(0);
}

The 6 phases of a Compiler are –


1. Lexical Analysis Phase
2. Syntax Analysis
3. Semantic Analysis
4. Intermediate Code Generation
5. Code Optimizer
6. Code Generation

Difference between Compiler & Interpreter


Compiler Interpreter
1 Compiler works on the complete Interpreter program works line
program at once. It takes the by line. It takes one statement
entire program as input. at a time as input.
2 Compiler generates No intermediate object code is
intermediate code called the generated,
object code, which further
requires linking,

3 Compiled program takes more More Memory efficient as no


memory , because the entire object code is generated.
object code has to reside in the
memory

4 Compiler executes conditional Interpreter executes


control statements and logical conditional control statements
constructs faster than an at a much slower speed.
Interpreter

5 It generates the error message Continues translating the


only after scanning the whole program until the first error is
program for syntactical and met, in which case it stops. The
other errors rest of the program will not be
checked until the existing error
is removed.

6 A compiled language is more Debugging is easy because the


difficult to debug. interpreter stops and reports
errors as it encounters them.

7 It takes large amount of time to It takes less amount of time to


analyze the source code but the analyze the source code but
overall execution time is the overall execution time is
comparatively faster. slower.

8 Programming language like C, Programming language like


C++ use compilers. Python, Ruby, Matlab, Pearl use
interpreters.

STEPS TO WRITE C PROGRAMS -


 Create the program
 Compile the Program
 Debug the Code
 Run/Execute the code to get the required output.

Source Code Object Code


Program that we write is Machine
called the Source Code language
Compilation Execution
OUTPUT

Compilation:
The process of translating source code written in high level to low level machine code is
called as Compilation.
The compilation is done by a special software known as compiler.
The compiler checks source code for any syntactical or structural errors and generates
object code, if source code is error free.

Execution:
Running the compiled Object file in order to see the output is what is known as
Execution.

File Extensions:

 File Extension used to save C programming files: Source file  .c


 Header Files containing predefined functions and various preprocessor statements
 .h
 Object Files – Source code in Binary Form  .obj
 Executable Files - The linker link together several object files to produce a binary
file that can be directly executed  .exe

Differences –

Source Code Object Code


1 A programmer generates a A compiler or any other type of
source code. Thus, it is translator generates an object code.
human-generated. Thus, it is machine-generated.
2 Source code is high level code. Object code is low level code.
3 Source code is written in plain Object code is translated code of
text by using some high-level source code. It is in binary format.
programming language.
4 Any human can understand a A machine can understand an object
source code. code- not a human.
5 Machines cannot directly Any machine can directly
understand a source code understand as well as execute an
unless translated. object code.
6 We write these types of codes An assembler, a compiler, or any
in various high-level other form of translator writes these
languages, such as Python, codes into the machine language fro
Java, C, C++, or the assembly the source code.
language.
7 One can easily modify these You cannot modify these codes.
codes.
8 Source code is input to It is a system-specific type of code
compiler or any other as it easily runs on machines
translator.
9 It is not a system-specific type Object Code is System Specific.
of code.

C: Program Structure
General Structure of a C Program –
Documentation Section:
 Also known as commenting section.
 Comments are ignored by compilers and are used to provide documentation to
help anyone to get an overview of the program.

Preprocessor directives:
 In a C program, the statements which start with the Hash symbol (#) are called
preprocessor directives.
 The C program provides a lot of inbuilt preprocessor directives that are handled by
the pre-processor before the compiler starts execution.
 The C Preprocessor is not a part of the compiler but is a separate step in the
compilation process.

Preprocessor Directive

File Inclusion Conditional Compilation Macros

 Pre-processor directives in C language –

#define #ifdef #if


#include #ifndef #else
#undef #error #elif
#pragma #endif

Link Section
 In C we have Header Files - files that contains a set of predefined standard library
functions.
 The Link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.

List of Header files in C -

Header File Description


stdio.h Input/Output Functions
conio.h Console Input/Output Functions
stdlib.h General Utility Functions
math.h Mathematical Functions
limits.h Size of basic datatypes
string.h String Functions
ctype.h Character Functions
time.h Date and Time Functions
float.h Limits of Float types
wctype.h Functions used to determine the type contained in wide
character data

Definition Section
 The definition section defines all symbolic constants.
Say for example –
#define PI=3.14

Global Declaration Section


 This part of the code is the part where the global variables (Variables that can be
used throughout the program) and user-defined functions are declared in this part
of the code.

Main Function Section


 Every C-programs needs to have the main function.
 The compiler starts executing C program from main() function.

Subprogram Section:
 All the user-defined functions are defined in this section of the program.
 These functions are used to perform a specific task.
 These functions are called in the main() function.

Some Key points


Rule 1:
All statement should be written in lowercase letters.

Rule 2:
Uppercase letter can be used only for symbolic constants.

Rule 3:
Blank spaces may be inserted between the words. This improves the readability of
statements.

Rule 4:
End of each C statement, that does not have a body - must be marked with a semicolon.
 All printf(), scanf() or any other function calls.
 All declarations like variables, constants, function, arrays, structures, unions etc
must be terminated by semicolon.
 All expressions must be terminated by the semicolon (;)

Rule 5:
Opening and closing "braces" must be balanced. They indicate a block (Statements
inside a block is considered as a single unit)

Rule 6:
Program must contain a main() function, if the program needs to be executed and
to get the output.

Rule 7:
C Programming Language is a case-sensitive programming language.

Rule 8:
We should remember to comment/document the code properly.

Rule 9:
Indentation is not compulsory for the compiler. But it’s most important while writing the
program. An indented code is easy to read and edit efficiently.

Rule 10:
White Spaces (ie tab space and space bar) are ignored.

C Program Example
Documentation
Section

Link Section

Global Declaration
Section

main()
Function
Section

Subprogram
Section

COMMENTS
 Comments are non-executable statements; they are not going to affect the
program’s output in anyways.
 Comments are optional. It is not mandatory to add comments within a program.
 Comments are not case-sensitive.
 It can be placed anywhere within a program.

Types of Comments –
C programming supports 2 types of Comments:

Comments

Single Line Multi - Line


Comments Comments

Symbol Used:
Symbol Used:
/* Whatever statements given
// This Line is a Comment within this is treated as a comment
*/

KEYWORDS
 Also known as Reserved Words (or) Pre-defined Words
 They convey a special meaning (or) purpose and can only be used in a specified
manner.
 All of C language Keywords are in Lower-case
 C language supports 32 keywords which are given below.

int long char float


double short signed unsigned
auto register extern static
if else for while
do switch case default
break continue goto sizeof
void return const typedef
struct union enum volatile

IDENTIFIERS
An identifier is a user-defined / Programmer defined names
There are many places within a program where the user must specify a name –
 Variables
 Functions
 Constants
 Arrays
 Pointers
 Structures
 Enums
 Unions

Rules that need to be followed:

1. Some compilers accepts max of 31 characters


2. Must begin with an alphabet (uppercase / lowercase), or underscore symbol ( _ ).
Subsequent characters can be another alphabet, digit, or underscore.

VALID NAMES INVALID NAMES


 age  123age
 Fname  @mail
 _mark  #tag
 _123

3. C language is Case-sensitive – Uppercase letters and Lowercase letters are treated


differently.
All of the below names are treated differently -
age AGE Age AGe AgE aGE agE

4. Keywords cannot be used as an Identifier.

VALID NAMES INVALID NAMES

 IF × if
 WHILE × while
 SIGNED × signed
 Else × else
 SWitch × switch

5. No special characters (! @ # $ % ^ & * ...etc) are allowed in a name.

INVALID NAMES

× age-20
× email@
× #tag
× gmail.com

6. Blank spaces are not allowed in-between the names.

VALID NAMES INVALID NAMES

 avg_marks × avg marks


 first_name × first name
 last_name × last name
7. Name of identifier cannot be exactly same as of name of another identifier within the
scope of the function (inside a block).

Example:
#include<stdio.h>
int main()
{
int ivar = 15;
float ivar = 20.5; // ERROR

printf("%d",ivar);
return 0;
}

8. Suppose we are making use of any header file in our program, there is one thing we
must pay attention to –Header files consist of pre-defined functions and variables. We
cannot make use of the same as our Identifier names.
Let us take example of the <math.h> Header file.
It consists of a pre-defined constant variable M_PI.
If we write our program as below – It will generate ERROR

Example:
#include<stdio.h>
#include<math.h>
int main()
{
int M_PI = 25;
printf("%d",M_PI);
return 0;
}

Programming Language can be classified into 2 types

Statically Typed Languages category


While creating a variable to store the data – we follow a specific syntax:
datatype varName = value;
There exists a relationship between the data type and the variable. Without the
mentioning of the data type it is not possible for us to create the variable. This
declaration helps the compiler to allocate the needed memory to store the value of
the variable.
Programming languages: C, C++, Java, C# follows this pattern.
Example
int a = 10;
float b = 20.56;
char ch = 'a';
double d = 78965.025;

Dynamically Typed Languages category


While creating a variable there is no need to mention the data type. We follow the
below given syntax:
varName = value
There exist no relationship/binding between the data type and the variable
explicitly. Based on the value assigned to the variable, the interpreter fixes its type
automatically.
Programming languages: Python, JavaScript, Ruby
Example:
name = "Python" # Data Type: str (String)
version = 3.10 # Data Type: float
founded = 1989 # Data Type: int (Integer)

As mentioned, based on the value that we are going to assign for the variable, the data
type is going to be decided by the interpreter.

DATA TYPES
Why to use Data Types?
o It tells the compiler the type of information we are going to store within the
variable.
o Memory Allocation - how much bytes of memory needs to be allocated for a
variable is decided based on the data type.

Data Types in C can be categorized as


Primary Data Type
These are the fundamental data types of
the C Language –
 int: used to store whole numbers.
 char: used to store a single
character.
 float: used to store decimal /
fractional value.
 double: used to store decimal /
fractional value (bigger number
compared to that of float)
 void: means Nothing. It is used as
a data type for Functions and also
for creating Pointers

Derived Data Type


A derived data type is defined using combination of modifiers along with the primitive
data type, with modified behaviour and property.

User-defined Data Type


C Language also supports the definition of custom data type, based on the program’s
requirement we can create our own data types with the help of the existing primitive
data types.

C Language: Data Types, Size and Range as on a 16-bit Machine


Data Types Size in Bytes Range
char 1 (8 bits) -128 to 127
signed char
unsigned char 1 (8 bits) 0 to 255
int 2 (16 bits) -32768 to 32767
signed int
unsigned int 2 (16 bits) 0 to 65535
short int 1 (8 bits) -128 to 127
signed short int
unsigned short int 1 (8 bits) 0 to 255
long int 4 (32 bits) -2147483648 to 2147483647
signed long int
unsigned long int 4 (32 bits) o to 4294967295
float 4 (32 bits) 3.4E-38 to 3.4E+38
double 8 (64 bits) 1.7E-308 to 1.7E+308
long double 10 (80 bits) 3.4E-4932 to 1.1E+4932

C Language: Data Types, Size and Range as on a 32-bit Machine


Integer Data Types
For an integer type of N
bits:

Signed: The range is from


−2N−1 to 2N−1−1. One bit is
for the sign.

Unsigned: The rang


e is from 0 to 2N−1. All bits
are for magnitude.

Floating-Point Data Types

C Language: Data Types, Size and Range as on a 64-bit Machine


Difference between float and double
float double
Similarity: Both double and float are used to represent real numbers that
have a fractional component in it.
It has single precision. It has the double precision, or you can
say two times more precision than
float.
Has a precision of 6-7 decimal Has a precision of 15-16 decimal
places places.

float type has 32-bit storage: 4 double type has 64-bit storage: 8 bytes
bytes

Range: 1.4e-045 to 3.4e+038 Range: 4.9e-324 to 1.8e+308

Bit Representation: Bit Representation:


1 bit represent sign bit. 1 bit represent sign bit.
8 bit represent exponent. 11 bit represent exponent.
23 bits represent mantissa. 52 bits represent mantissa.

There will be no data loss when the Data loss is expected when double is
float is converted to double as float converted to float.
has a lower range than double.

Less accurate. More Accurate.

VARIABLES
What is a Variable?
They are like containers (or) boxes which are going to be used to store data
(Values). Temporary Storage.

Syntax: Declaring a Single Variable


datatype variable_name;

Example:
int a;
float marks;
double salary;
char gender;
char name[50];

Syntax: Declaring Multiple Variables


datatype V1, V2, V3 ….., VN;

Here all the variables – V1, V2, V3 and so on belongs to the same data type (With which
they are declared)

Example:
int a, b, c, d;
float m1,m2;
double avg, percentage;

Syntax: Declaration & Definition at the same time


datatype variable_name = value;

Example:
int a = 25;
float marks = 85.3;
double salary = 87523.254;
char gender = ‘F’;
char name[50] = “Anushya Srikanth”;

NOTE:

Point 1: While declaring the type of variable we can also initialize it as shown below –
int i=10, j=25 ;
float a=1.5, b=1.99 + 2.4 * 1.44 ;

Point 2: The order in which we define the variables is sometimes important sometimes
not.
For Example: (Not Important)
int i=10, j=25;
int j=25, i=10;

For Example: (Important)


float a=1.5, b=a+3.1;
float b=a+3.1, a=1.5; // ERROR

The following statements would work


int a, b, c, d ;
a = b = c = 10; // VALID
However, the following statement would not work
int a = b = c = d = 10; // ERROR

MODIFIERS
• Modifiers are prefixed with basic data types to modify (either increase or decrease)
the amount of storage space allocated to a variable.
• There are 5 modifiers (Keywords) available in C -.
– short
– long
– signed
– unsigned
– long long

signed and unsigned keywords


• The main difference between a signed and an unsigned number is –
The ability to use negative numbers

When we declare the data type as


unsigned int  then we are restricting the type of values that this data type/variable
can accepts as zero or greater (Only Positive numbers).
Example:
unsigned int a = 100;
unsigned char ch = 'F';

signed int  then the numbers are more natural with a range that includes both
negative to positive values. This is also the default modifier.
That is – incase we do not mention any modifier while creating the variable, the compiler
will create it as a signed variable.
Example:
signed int a = 100;
signed int b = -56;
int c = 25;
int d = -89;

short, long and long long keywords


In a 32-bit Processor:
int occupies 2 bytes of memory.
If we want to increase the range of int then we can use it as:
• long int  4 bytes
Example:
long int salary = 78596;
long int distance = 456321;

In a 64-bit Processor:
int occupies 4 bytes of memory.
If we want to increase the range of int then we can use it as:
• long int  8 bytes
Example:
long int a = 7852596;
long int b = 4546321;
In a 64-bit Processor:
int occupies 4 bytes of memory.
If we want to decrease the range of int then we can use it as:
• short int  2 byte.
Example:
short int age = 18;
short int alpha = 26;
FORMAT SPECIFIERS
 The format specifier is used during input and output.
 It is a way to tell the compiler what type of data is in a variable during taking input
using scanf() or printing using printf().

Data Format Meaning


Type
%hi Represents - signed short int
Can also use the %d format specifier instead of %hi
int %hu Represents – unsigned short int
Can also use the %u format specifier instead of %hu
%d Represents - signed int
%u Represents - unsigned int
%ld Represents - signed long int
%lu Represents - unsigned long int
%i Represents a decimal integer which detects the base
automatically.
It can take the input number in form of decimal or octal
or hexadecimal formats.
%o Octal representation of Integers
%X Hexadecimal representation of Integers
%x

%f Represents - floating-point value  float.


float %lf Represents - floating-point value  double
double %Lf Represents a long double value

char %c Represents both signed char & unsigned char data types

string %s Represents a string value of characters (char array).

%% Represents the symbol %

%p Used to print an address (pointers)

printf() Function
 The printf() is a Built-in / Pre-defined / Library Function
 To use printf() in our program, we need to include <stdio.h> header file [Standard
Input Output] within our source code.

General Syntax of the printf() Function:


int printf(“Control String”, arg1, arg2, arg3, ……. , argN);
Return value:
 It returns an integer value that represents the number of characters that it has
printed on the output screen successfully - including all the white space & special
characters, or negative value if an output error or an encoding error.
Note: Nested printf() is possible – writing one printf() statement inside another. It can be
nested to N levels; there is no limit.
scanf() Function
This pre-defined function is available within the <stdio.h> header file.
Syntax:
scanf(“Format Specifier”, &v1, &v2, …., &vn);
Return Type:
It returns total number of inputs scanned successfully, or EOF if input failure occurs
before the first receiving argument was assigned.

ESCAPE SEQUENCE
It tells the compiler to escape from the way these characters would normally be
interpreted. Every character has a special meaning.

Escape Character Description


Sequenc Representation
e
\n Newline Moves to a new line
\t Horizontal Tab Moves to the next horizontal tab setting
\v Vertical Tab Moves to the next vertical tab settings
\b Backspace Moves back one space
\r Carriage return Carriage return – moves the cursor to the start of
the current line.
Used for overprinting.
\a Alert Issues an alert – usually a bell sound
\\ Backslash Inserts a backslash character within a string.
\? Question mark Inserts a question mark character
\’ Single Quotation Inserts a single quote character within a string
\” Double Quotation Inserts a double quote character within a string

Functions: gets & puts()


 Input Function: gets() – used to read a string. It can read the string value along
with white spaces also.
In an Online Compiler: gets() is a deprecated Function.
 Output Function: puts() – used to display a string.
Syntax:
gets(string_variable);
puts(string_variable);

Function: getchar()
Input Function – present within the <stdio.h> Header File.
The getchar() function is used to read a single character and store it within the variable.
Syntax:
character_variable = getchar();
Example:
char ch;
ch = getchar();

When this function is executed, the computer will wait for the user to input a single
character value and then press the Enter key. As soon as the key is pressed, the function
will read the value and store it within the variable.

Function: putchar()
Output Function – present within the <stdio.h> Header File.
The putchar() function is used to display a single character as its output.
Syntax:
putchar(character_variable);
Example:
char ch = ‘a’;
putchar(ch);

When the above code is executed, the putchar() function displays the variable of the
variable passed within its parameter.
We cannot make use of any control string or escape sequence inside of the putchar()
function.

Function: getch()
Input Function – present within the <conio.h> Header File.
The getch() function is used to read a single character and store it within the varia
Syntax:
character_variable = getch();
Example:
char ch;
ch=getch();
Function: putch()
Output Function – present within the <conio.h> Header File.
The putch() function is used to display a single character as its output.
Syntax:
putch(character_variable);
Example:
char ch = ‘@’;
putch(ch);

Function: getche()
Input Function – present within the <conio.h> Header File.
The getche() function is used to read a single character and store it within the varia
Syntax:
character_variable = getche();
Example:
char ch;
ch=getceh();

fgets() Function
It is used to read a string value from the File Stream mentioned as the parameter value.
It has the capacity to read the string values with whitespaces included.
Syntax:
fgets(char_Array_Name, int Size_of_the_charArray,
FileStream_where_characters_are_read_from);

fputs() Function
Use d to print the charArray on the mentioned File Stream
Syntax:
fputs(charArray, File_stream);

How it differs from getchar() & getch() functions


getchar()  After entering a character, we have to press the enter key then only
the value will be taken and stored inside of the variable.
The entered character will be visible.

getch()  There is no need to press the enter key, as soon as the value is entered
by the user, the value will automatically be taken and stored within the variable.
And also the entered character will not be visible.

getche()  There is no need to press the enter key, as soon as the value is
entered by the user, the value will automatically be taken and stored within the
variable. And the entered character will be visible.
PROGRAMS FOR PRACTISE
Program: Welcome Message
#include<stdio.h>
int main()
{
printf("Hello, Welcome to C Programming");
printf("All the Best!")
return 0;
}

With: \n  Newline
#include<stdio.h>
int main()
{
printf("Hello, Welcome to C Programming\n");
printf("All the Best!")
return 0;
}

With: \t  Horizontal Tabspace


#include<stdio.h>
int main()
{
printf("Hello, Welcome to C Programming\t");
printf("All the Best!")
return 0;
}
---------------------------------------------------------------------------------------------
Program: printf() returning a value
#include <stdio.h>
int main()
{
int len = 0;
len = printf ("Hello, How are you doing?");
printf ("\nLength: %d\n", len);
return 0;
}
Output:
Hello, How are you doing?
Length: 25
---------------------------------------------------------------------------------------------
Program: Nested printf() and the return value of a printf() function
#include <stdio.h>
int main()
{
printf("%d",printf("Hello, Welcome to C."));
return 0;
}
Output:
Hello, Welcome to C Language.20

Explanation:
When we are having nested functions – the point to remember is that 1 st the inner most
printf() will get executed and then followed by the outer printf() statements.

#include<stdio.h>
int main()
{
int x = printf("Hello, Welcome to C."); // 20
printf("\nValue of x = %d", x);
return 0;
}
Output Screen -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
H e l l o , W e l c o m e t o C .
---------------------------------------------------------------------------------------------
Program: Spanning printf() across multiple lines.
#include <stdio.h>
int main()
{
printf ("Hello world, how are you?
I love C programming language.\n");
return 0;
}
Output: Compilation ERROR

We can avoid the error by using / (backslash) which means Line continuity.
#include <stdio.h>
int main() {
printf ("Hello world, how are you? \
I love C programming language.\n");
return 0;
}
Output:
Hello world, how are you? I love C programming language.
---------------------------------------------------------------------------------------------
Program: Format Specifiers with printf() Function
#include<stdio.h>
int main()
{
// String: Character Array
char name[30] = "Anushya Srikanth";
// Single Character
char gender = 'F';
// Integer
short int age = 30;
// Integer
long int mbno = 9381817369;
// Real Numbers
float marks = 85.2;
double cgpa = 9.2;

printf("Person's Information");
printf("\nName: %s", name);
printf("\nGender: %c", gender);
printf("\nAge: %hu", age);
printf("\nMarks: %.2f", marks);
printf("\nCGPA: %.2lf", cgpa);
return 0;
}
---------------------------------------------------------------------------------------------
Program: Printing Decimal, Octal and Hexadecimal Numbers
#include<stdio.h>
int main()
{
int a = 12;
printf("Decimal a = %d\n", a);
printf("Octal a = %o\n", a);
printf("Hexadecimal a = %x\n", a);
return 0;
}
---------------------------------------------------------------------------------------------
Program: Printing a % symbol in the Output Window
Expected Output: I scored 98% in my exam
#include<stdio.h>
int main()
{
printf("I scored 98%% in my exam");
return 0;
}
---------------------------------------------------------------------------------------------
Program: Getting Inputs from the User and Printing them
#include<stdio.h>
int main()
{
char name[30];
char gender;
short int age;
long int mbno;
float marks;
double cgpa;

// User Inputs
printf("Enter your Name: ");
scanf("%s", &name);
printf("\nEnter your Age: ");
scanf("%hd", &age);
printf("\nEnter your Mobile Number: ");
scanf("%ld", &mbno);
printf("\nEnter your Gender: ");
scanf("%*c%c", &gender);
printf("\nEnter your Marks: ");
scanf("%f", &marks);
printf("\nEnter your CGPA: ");
scanf("%lf", &cgpa);

// Printing
printf("\n\nPerson's Information");
printf("\nName: %s", name);
printf("\nGender: %c", gender);
printf("\nAge: %hd", age);
printf("\nMobile Number: %ld", mbno);
printf("\nMarks: %.2f", marks);
printf("\nCGPA: %.2lf", cgpa);
return 0;
}
---------------------------------------------------------------------------------------------
Program: It is permitted to mix data types in one print statement
#include <stdio.h>
int main(void)
{
int a = 20;
float b = 45.23;
char c = 'F';
printf("a=%d, b=%.2f, c=%c",a,b,c);
return 0;
}
Output:
a=20, b=45.23, c=F
---------------------------------------------------------------------------------------------
Program: Reading a Single Character and a String, printing the values.
#include <stdio.h>
int main()
{
char a;
char prog_name[50];
printf("Enter a Single Character: ");
scanf("%c",&a);
printf("\nName of your favourite Programming Language: ");
scanf("%s",&prog_name);
printf("\nSingle Character value - %c", a);
printf("\nMy favourite Programming Language is %s", prog_name);
return 0;
}

Input:
Enter a Single Character: A
Name of your favourite Programming Language: Java
Output:
Single Character value - A
My favourite Programming Language is Java
--------------------------------------------------------------------------------------------- Program:
Relationship between char and int data types.
#include <stdio.h>
int main()
{
char a;
printf("Enter a Single Character: ");
scanf("%c",&a);
printf("\nSingle Character value - %c", a);
printf("\nSingle Character value - %d", a);
printf("\nASCII value of %c is %d",a,a);
return 0;
}

Input:
Enter a Single Character: A
Output:
Single Character value - A
Single Character value - 65
ASCII value of A is 65
---------------------------------------------------------------------------------------------
Program: Relationship between int and float data types.
#include<stdio.h>
int main()
{
int v1 = 4/5;
printf("v1 = %d",v1);

float v2 = 4/5;
printf("\nv2 = %f",v2);
float v3 = 4.0/5.0;
printf("\nv3 = %f",v3);

return 0;
}
Output:
v1 = 0
v2 = 0.000000
v3 = 0.800000
---------------------------------------------------------------------------------------------
Program: To find the size of the Data types (How much of Memory is getting allocated).
The output of this program may differ based on your System’s Configuration.

#include <stdio.h>
int main()
{
/* sizeof(data_type):
This is a function which returns the number of bytes occupied by the data type
name passed within the parenthesis. */

// Integer Types
printf("Size of int : %d", sizeof(int));
printf("\nSize of unsigned int : %d", sizeof(unsigned int));
printf("\nSize of short int : %d", sizeof(short int));
printf("\nSize of unsigned short int : %d", sizeof(unsigned short int));
printf("\nSize of long int : %d", sizeof(long int));
printf("\nSize of unsigned long int : %d", sizeof(
unsigned long int));

// Real Numbers
printf("\nSize of float : %d", sizeof(float));
printf("\nSize of double : %d", sizeof(double));
printf("\nSize of long double : %d", sizeof(long double));

// Character
printf("\nSize of char : %d", sizeof(char));

// void
printf("\nSize of void : %d", sizeof(void));

return 0;
}

Output:
Size of int : 4
Size of unsigned int : 4
Size of short int : 2
Size of unsigned short int : 2
Size of long int : 8
Size of unsigned long int : 8
Size of float : 4
Size of double : 8
Size of long double : 16
Size of char : 1
Size of void : 1
---------------------------------------------------------------------------------------------
Program: To find the Maximum and Minimum value (Range) of a Data Type
 <limits.h> defines sizes of integral types.
 The limits for fundamental floating-point types are defined in <float.h>

#include <stdio.h>
#include <limits.h>
#include <float.h>
int main( void )
{
printf( "Ranges for integer data types in C\n\n" );
printf( "------------------------------------------------------------\n");
printf( "int8_t %20d %20d\n" , SCHAR_MIN , SCHAR_MAX );
printf( "int16_t %20d %20d\n" , SHRT_MIN , SHRT_MAX );
printf( "int32_t %20d %20d\n" , INT_MIN , INT_MAX );
printf( "int64_t %20lld %20lld\n" , LLONG_MIN , LLONG_MAX );
printf( "uint8_t %20d %20d\n" ,0 , UCHAR_MAX );
printf( "uint16_t %20d %20d\n" ,0 , USHRT_MAX );
printf( "uint32_t %20d %20u\n" ,0 , UINT_MAX );
printf( "uint64_t %20d %20llu\n" , 0 , ULLONG_MAX );
printf( "\n" );
printf( "================================================
=\n\n");
printf( "Ranges for real number data types in C\n\n" );
printf( "------------------------------------------------------------\n");
printf( "float %14.7g %14.7g\n" , FLT_MIN , FLT_MAX );
printf( "double %14.7g %14.7g\n" , DBL_MIN , DBL_MAX );
printf( "long double %14.7Lg %14.7Lg\n" , LDBL_MIN , LDBL_MAX );
printf( "\n" );
return 0;
}
Output:
---------------------------------------------------------------------------------------------
Program: What happens when we go beyond the range of the data type?

Example: char data type


#include <stdio.h>
int main()
{
unsigned char c = 255;
c = c + 10;
printf("c=%d",c);
return 0;
}
Output:
c=9
Explanation:
unsigned char c  occupies 1 byte of memory and the range is 0 to 255.
So c = 255; is a valid statement.
When we say c = c + 10;  c = 255 + 10  c=265, which is beyond its capacity. So,
what the compiler does is that it applies Modulo operation 2 n
where n represents the number of bits.
1 byte = 8 bits
265 % 28  265%256 = 9 will be the output.

Example: int data type


#include <stdio.h>
int main()
{
unsigned int i = 4294967295;
i = i + 20;
printf("i=%d",i);
return 0;
}
Output:
i=19
Explanation:
int occupies – 4 bytes : 232 = 0 to 4294967295
So i = 4294967295; is a valid statement.
When we say i = i + 20;  c = 4294967295+ 20  i=4294967315 which is beyond its
capacity. The compiler does is that it applies Modulo operation 2 n -> where n represents
the number of bits.
4 byte = 32 bits
4294967315 % 232  4294967315 % 4294967296 = 19 is the output.
---------------------------------------------------------------------------------------------
Program: Difference between signed and unsigned integers
#include <stdio.h>
int main()
{
signed int n1; // Can accept both Positive & Negative Values
unsigned int n2; // Can accept only Positive Values
printf("Enter a value: ");
scanf("%d", &n1);
printf("\nEnter a value: ");
scanf("%u", &n2);
printf("\nn1=%d and n2=%u",n1,n2);
return 0;
}

Execution 1:
Enter a value: 50
Enter a value: 25
n1=50 and n2=25

Execution 2:
Enter a value: -50
Enter a value: 25
n1=-50 and n2=25

Execution 3:
Enter a value: -50
Enter a value: -1
n1=-50 and n2=4294967295
Explanation:
This may differ according to the system configuration:
unsigned int occupies 4 bytes. Range: 0 to 4294967295  UINT_MAX
The expression -1 is of type int and has the value -1.
The initializer converts this value from int to unsigned int.
The rules for signed-to-unsigned conversion say that the value is reduced
modulo UINT_MAX + 1
So, -1 will convert to UINT_MAX (which is probably 4294967295 (or) 0xffffffff
---------------------------------------------------------------------------------------------
Program:
An input field may be skipped by specifying * in the place of field width specification.
#include <stdio.h>
int main() {
int a,b,sum;
printf("Enter 2 Numbers: ");
scanf("%d %*d %d", &a, &b);
sum = a+b;
printf("\n%d+%d = %d",a,b,sum);
return 0;
}
Output:
Enter 2 Numbers: 12 25 50
12+50 = 62
Explanation:
12 is assigned to the variable ‘a’
25 is skipped because of * in the %d
50 is assigned to the variable ‘b’
Hence the output -> a+b  12+50 = 62
---------------------------------------------------------------------------------------------
Program: Problem with scanf() while reading a String
#include <stdio.h>
int main()
{
char name[20];
printf("Enter your Name: ");
scanf("%s", name);
printf("Welcome %s", name);
return 0;
}
Output:
Enter your Name: Anushya
Welcome Anushya

Output:
Enter your Name: Anushya Srikanth
Welcome Anushya

Syntax: scanf("%[^\n]s", variableName);

#include <stdio.h>
int main()
{
char name[20];
printf("Enter your Name: ");
scanf("%[^\n]s", name);
printf("\nWelcome %s", name);
return 0;
}
Output:
Enter your Name: Anushya Srikanth
Welcome Anushya Srikanth
---------------------------------------------------------------------------------------------
Program: scanf() to accept any kind of Separator – By using the %*c
When we are using this format with the scanf() function, we can accept any kind of
character as a separator.
#include <stdio.h>
int main ()
{
int a,b,c;
// Enter 3 Numbers - separated by a Separator
scanf("%d%*c%d%*c%d", &a, &b, &c);
printf("a=%d, b=%d, c=%d",a, b, c);
return 0;
}
Input:
40,20,85
Output:
a=40, b=20, c=85

Input:
40-20-60
Output:
a=40, b=20, c=60

Input:
40 20 60
Output:
a=40, b=20, c=60
---------------------------------------------------------------------------------------------
Program: scanf() return value
#include <stdio.h>
int main ()
{
int a,b,c,n,sum=0;
printf("Enter 3 Numbers: ") ;
n = scanf("%d%d%d", &a, &b, &c);
sum = a+b+c;
printf("\n%d + %d + %d = %d",a,b,c,sum);
printf("\nscanf() returns - %d",n);
return 0;
}
Input:
Enter 3 Numbers: 10 20 30
Output:
10 + 20 + 30 = 60
scanf() returns – 3
Explanation:
All the 3 values passed are integer, hence valid. So the scanf() reads all the 3 values and
store it in to the variable. And returns the value 3

Now let us try some different inputs –

Example 1 -
Input:
10 20 A
Output:
10 + 20 + 0 = 30
scanf() returns – 2
Explanation:
Out of the 3 values – 1 st and 2nd value are integers and hence valid, but the 3 rd is a char
data, hence the scanf() will read only the first two values and store it into the
appropriate variables. Hence the scanf() will return the value 2

Example 2 -
Input:
10 A anu
Output:
10 + 1408913600 + 0 = 1408913610
scanf() returns – 1
Explanation:
Out of the 3 values – only the 1st value is an integer. The remaining 2 values inputted
does not match with the expected data type – which is integer. Hence the scanf() will
only read one value and store it in to the variable and returns the value 1

Example 3 -
Input:
10 A 40
Output:
10 + -1696955568 + 0 = -1696955558
scanf() returns – 1
Explanation:
1st and the 3rd value is an integer and the 2nd value is a character. The scanf() will read
the 1st value successfully and store it into the variable. 2 nd value that the scanf() is trying
to read should be an integer value but it encounters a char. So, the scanf() will no longer
continue its work and will move to the next statement following the scanf() function.
Hence the function returns the value 1.

Example 4 -
Input:
ABC
Output:
32764 + -1072327920 + 0 = -1072295156
scanf() returns - 0
Explanation:
All the 3 values inputted are of char types, hence the scanf() function which has been
written to read integer values will not be able to read any value, and it returns the value
as 0.
---------------------------------------------------------------------------------------------
Program: Difference between using %d and %i Format specifiers
#include <stdio.h>
int main ()
{
int a,b,c;
/* %i allows us to read an integer
value in any of its form -
Decimal, Octal and Hexadecimal. */
printf("Enter a Decimal Number: ");
scanf("%d",&a);
printf("\nEnter a Hexadecimal Number: ");
scanf("%i",&b);
printf("\nEnter a Octal Number: ");
scanf("%i",&c);

printf("\nDecimal Values: a=%d , b=%d , c=%d",a,b,c);


return 0;
}
Input:
Enter a Decimal Number: 12
Enter a Hexadecimal Number: 0x12
Enter a Octal Number: 012
Output:
Decimal Values: a=12 , b=18 , c=10
---------------------------------------------------------------------------------------------
Program: using getchar() and putchar()
#include<stdio.h>
int main()
{
char alpha;
printf("\n Enter a Single Character : ");
alpha = getchar();
putchar(alpha);
return 0;
}
---------------------------------------------------------------------------------------------
Program: using getch() and putch()
#include<stdio.h>
#include<conio.h>
int main()
{
char alpha;
printf("\n Enter A Character : ");
alpha=getch();
printf("\n The User has entered : ");
putch(alpha);
return 0;
}
---------------------------------------------------------------------------------------------
Program: using getche() function
#include<stdio.h>
#include<conio.h>
int main()
{
char alpha;
printf("\n Enter a Character : ");
alpha=getche();
printf("\n The Entered Character is : ");
putch(alpha);
return 0;
}
---------------------------------------------------------------------------------------------
Program: using gets() and puts()
#include<stdio.h>
int main()
{
char name[20];
puts("Enter a Name : ");
gets(name);
puts("\n The User has Entered : ");
puts(name);
return 0;
}
---------------------------------------------------------------------------------------------
Program: Using fgets() & fputs() function
#include <stdio.h>
int main()
{
char email[30];
// Enter your email ID:
fgets(email, sizeof(email), stdin);
fputs("Contact me at - ",stdout);
fputs(email, stdout);
return 0;
}
Output:
[email protected]
Contact me at - [email protected]
---------------------------------------------------------------------------------------------Program:
Using fgets() & fputs() function
#include<stdio.h>
int main()
{
char s[70];
// Enter a Sentence
fgets(s, sizeof(s), stdin);
fputs("You have entered: ",stdout);
fputs(s, stdout);

return 0;
}
Output:
Welcome to C Programming
You have entered: Welcome to C Programming
---------------------------------------------------------------------------------------------

You might also like