C Notes 1
C Notes 1
Prepared by:
Shuvadeep Bhattacharjee
University of Engineering and Management,
Kolkata-700156, India
Email ID: shuvadeep.bhattacharjee@uem.edu.in
INTRODUCTION TO ‘C’ PROGRAMMING
Overview of C language:
A program is a set of instructions that a computer can understand and execute to perform a specific task.
● Instructions are commands that a computer processor can understand and execute
● A programming language is the tool we use to write these instructions for the computer.
● Designed to handle a wide variety of problems and tasks, not specialized for any particular domain.
● Bridges the gap between high-level and low-level languages.
● Language that is closer to human language and further from machine code (low-level language).
Facts about C
Key Characteristics:
● Powerful and versatile: Can be used for a wide range of applications (operating systems, embedded
systems, game development, etc.).
● Efficient and fast: Compiles to machine code, resulting in high performance.
● Structured programming: Emphasizes modularity and code organization.
● Low-level access: Provides direct control over hardware, making it suitable for system-level programming.
● Can be compiled on a variety of computer platforms.
Why Learn C?
● Foundation for other languages: Many modern languages (C++, Java, Python) have roots in C.
● Improved problem-solving skills: Learning C enhances logical thinking and algorithmic
problem-solving abilities.
● Career opportunities: C is still widely used in various industries, offering excellent job prospects.
A C program can vary from 3 lines to millions of lines and it should be written into one or more text files
with extension ".c"; for example, hello.c.
C Environment setup:
(a) Text Editor (Windows Notepad/Vim editor) and (b) The C Compiler.
● The files you create with your editor are called source files typically named with the extension “.c”.
example, hello.c.
● It needs to be "compiled", to turn into machine language so that your CPU can actually execute the
program as per instructions given.
● Compiler will be used to compile the source code into final executable program
Using Terminal:
● gedit filename.c ( opens the file named filename.c in the text editor called gedit)
● gcc filename.c (tells the compiler to create an executable file named filename)
● ./a.out ( executes the compiled program)
Structure of C programming
● Every C program consists of one or more functions. One of the function is called main
○ The program will always begin by executing the main function
● Each function must contain :
○ Function heading consisting of function name, followed by optional list of
arguments enclosed in parentheses
○ A list of argument declarations
○ A compound statement consisting of remaining of the function
Writing First Program: Hello World
Let us look at a simple code that would print the words "Hello World":
Output:
Hello, World!
Sample C program
///Sum of two numbers
#include <stdio.h>
main()
{
○ #include: This is a directive to the C preprocessor, a special program that modifies the source
code before the actual compilation process begins.
○ <stdio.h>: stdio.h stands for "standard input/output header file". Header files contain
declarations for functions, variables, and other entities.
Variables:
Eg. int velocity, float temp; // velocity and temp are variables
C Comments:
Types of comments :
C tokens
● Smallest individual element that is meaningful to the compiler.
Tokens
Special
Keywords Identifiers Constants Strings Operators
symbols
Keywords:
● Pre-defined or reserved words that have special meaning to the compiler.
● Meant to perform a specific function
● Cannot be used as variable names
● Cannot redefine keywords
● 32 standard keywords supported
Identifiers:
● Names given to various entities like variables, functions, constants,etc
Examples of constants:
const int c=20;
Strings:
char name[]=”hello”;
Syntax:
char string_name[size]; 2. Character-by-Character
char name[20]; // Declares a string named 'name' with a maximum size of 20 Initialization:
characters
char name[20]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Header Files Inclusion
A header file is a file with extension.h which contains C function declarations and macro definitions to be
shared between several source files. All lines that start with # are processed by a preprocessor which is a
program invoked by the compiler.
#include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.
#include<conio.h>: not part of the standard C library. Primarily used for console input/output
operations such as such as getch() and clrscr()
Special Symbols:
● Symbols that trigger an action when applied to C variables and other objects
● The data items on which operators act are called operands
Operators
● Binary Operators: Those operators that require two operands to act upon.
○ + (Addition): Adds two operands.
○ - (Subtraction): Subtracts the second operand from the first. Int a,b=8,c=2,d,m,
a=b+c; // a=10
○ * (Multiplication): Multiplies two operands. d=b/c; // d=4
m=b%c; //m=0
○ / (Division): Divides the first operand by the second.
For example
#include <stdio.h>
main() {
int a = 10, b = 5;
int sum, difference, product, quotient, remainder;
sum = a + b;
difference = a - b;
product = a * b;
quotient = a / b;
remainder = a % b;
}
Question
Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this
temperature into Centigrade degrees.
Hierarchy of operations
Determine the hierarchy of operations and evaluate
i=2*3/4+4/4+8-2+5/8
Relational operator
# include <stdio.h>
int main ()
{
int a=10;
int b=10;
int result=a==b;
printf ("%d", result);
return 0;
}
Output: 1
Logical operator
Output:
Not eligible for student discount.
Problem:
The marks obtained by a student in 5 different subjects are input through the
keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.
Problem:
#include<stdio.h>
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ; Output:
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; Enter marks in five
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
subjects 60
50
if ( per >= 60 ) 70
printf ( "First division" ) ; 50
if ( ( per >= 50 ) && ( per < 60 ) ) 60
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
Second division
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
}
Assignment operator
● The assignment operator in C is =.
● It is used to assign a value to a variable.
Syntax:
variable_name = value;
Example:
float pi = 3.14159;
Bitwise operator
● Left shift(<<): Shifts the bits of the first operand to the left by the number of positions specified by the second
operand.
// Result
: // y = 20 (Binary: 00010100)
● Bitwise AND (&):Returns 1 in a particular bit position only if both bits in that position of the operands are 1.
Otherwise, it returns 0.
printf("a: %d (Binary: %08b)\n", a, a);
int a = 12; // Binary: 00001100
● To control the flow of your program based on whether certain conditions are true or false.
● Enable your program to make decisions and execute different blocks of code accordingly.
1. if Statement:
a. Executes a block of code only if a specified condition is true.
if (condition) {
}
Conditional Statements in C
2. if-else Statement:
● Executes one block of code if the condition is true and another block if the condition is false.
if (condition) {
} else {
}
Conditional Statements in C
} else if (condition2) {
} else if (condition3) {
// Code to be executed if condition1 and condition2 are false and condition3 is true
} else {
}
Write a program to find the greatest among the three numbers using
if-else condition
#include <stdio.h>
// Find the greatest number using if-else
statements
int main() {
if (num1 >= num2 && num1 >= num3) {
int num1, num2, num3, greatest;
greatest = num1;
} else if (num2 >= num1 && num2 >= num3)
// Get input from the user
{
printf("Enter three numbers: ");
greatest = num2;
scanf("%d %d %d", &num1, &num2, &num3);
} else {
greatest = num3;
}
// Print the greatest number
printf("The greatest number is: %d\n",
greatest);
return 0;
}
Nested if else
● Nested conditionals occur when one or more if...else statements are placed within the block of
another if...else statement.
● Allows for more complex decision-making logic.
Structure:
if (condition1) {
else {
// Code to be executed if condition1 is true
// Code to be executed if condition1 is false
if (condition2) {
if (condition3)
// Code to be executed if both
{
condition1 and condition2 are true
// Code to be executed if condition1 is false and
}
condition3 is true }
else {
else { // Code to be executed if neither condition1
// Code to be executed if
nor condition3 is true }
condition1 is true, but condition2 is false
}
}
}
Problem
Write a C program to determine if a person is eligible to donate blood based on
the following criteria:
return 0; }
Switch case
● Multi-way branching statement that allows you to execute different blocks of code based on the
value of an expression.
● Alternative to using a series of if-else if statements
Structure:
switch(expression) {
break;
}
Find grade of a student using switch case
switch (percentage / 10) {
default:
Note: >=60% 1st div
printf("Fail\n");
50-59% 2nd div
40-49% 3rd div }
40% Fail
}
Write a program to create a calculator application using switch case.
case '-':
#include<stdio.h> result=num1-num2;
int main () break;
{ case '*':
int num1, num2; result=num1*num2;
float result=0; break;
char operation; case '/':
printf ("Enter the first number : \n"); result=(float)num1/(float)num2;
scanf ("%d", &num1); break;
printf ("Enter the second number : \n"); case '%':
scanf ("%d", &num2); result=num1%num2;
printf ("Choose operation: \n"); break;
scanf (" %c", &operation); default:
switch(operation) printf("Invalid operation. \n");
{ }
case '+': printf ("The result is : %d %c %d = %.2f\n", num1,
result=num1+num2; operation, num2, result);
break; return 0;
}
Output: Enter the first number : 5 Choose operation: -
Enter the second number : 3 The result is : 5 - 3 = 2.00