C Programming Notes
C Programming Notes
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
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
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.
Output Run
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);
}
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:
Differences –
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
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.
Definition Section
The definition section defines all symbolic constants.
Say for example –
#define PI=3.14
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.
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
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.
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
IF × if
WHILE × while
SIGNED × signed
Else × else
SWitch × switch
INVALID NAMES
× age-20
× email@
× #tag
× gmail.com
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;
}
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.
float type has 32-bit storage: 4 double type has 64-bit storage: 8 bytes
bytes
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.
VARIABLES
What is a Variable?
They are like containers (or) boxes which are going to be used to store data
(Values). Temporary Storage.
Example:
int a;
float marks;
double salary;
char gender;
char name[50];
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;
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;
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 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;
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().
char %c Represents both signed char & unsigned char data types
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.
ESCAPE SEQUENCE
It tells the compiler to escape from the way these characters would normally be
interpreted. Every character has a special meaning.
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);
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;
}
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?
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
#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
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);
return 0;
}
Output:
Welcome to C Programming
You have entered: Welcome to C Programming
---------------------------------------------------------------------------------------------