[go: up one dir, main page]

0% found this document useful (0 votes)
18 views48 pages

C Notes 1

Uploaded by

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

C Notes 1

Uploaded by

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

Programming for Problem Solving

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.

C program created by Dennis Ritchie at Bell Labs in the early 1970s.


C is a general-purpose, middle level programming language.

● 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

● C was invented to write an operating system called UNIX.


● C is a successor of B language, which was introduced around 1970.

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:

Need to have two softwares available on your computer

(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

Running C code in ubuntu:

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":

#include <stdio.h> // Header file includes function for input/output

main() // Main function executed when you run the program

{ // Statements within curly braces are executed sequentially

/* my first program in C */ // Commented line

printf("Hello, World! \n") ; // printf function for printing statement


}

Output:
Hello, World!
Sample C program
///Sum of two numbers

#include <stdio.h>
main()
{

int a,b,c; // integer variables declaration


printf(“\n Enter the numbers: \n”); // interacts with the user
scanf(“%d%d”,&a,&b); // inputs integer variable
c=a+b; // add two numbers
printf(“\n The sum of %d and %d is %d\n”, a,b,c); // control characters for printing value of a

Output: The sum of 5 and 10 is 15


printf and scanf functions
● scanf() function to read input value from keyboard
● scanf function generalized form:
○ scanf(“ <format string>”, <list of variables>);
○ ampersand (&) before the variables is a must.
○ & is an ‘Address of’ operator.
○ at which memory location should it store the value supplied by the user from the keyboard.
Eg. scanf("%d %f %s", &age, &height, name);

● printf( ) function to output a message


● printf function generalized form:
○ printf ( "<format string>", <list of variables> ) ;
○ <format string> can contain,
■ %f for printing real values
■ %d for printing integer values
■ %c for printing character values
Eg. printf ( "%d %d %f %f", p, n, r, si ) ;
Preprocessor directive: #include <stdio.h>

○ #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:

● Named memory locations used to store data


● Act as containers that hold values which can change during program execution.

Eg. int velocity, float temp; // velocity and temp are variables

Functions: self-contained blocks of code that perform a specific task

● int main() is the main function where program execution begins.


● /*...*/ : Comments will be ignored by the compiler
● printf function causes the message "Hello, World!" to be displayed on the screen.
● line return 0; terminates main()function and returns the value 0.
Basic Syntax:

C Comments:

● Human-readable notes in the source code


● Makes the program easier to read and understand

Types of comments :

● Single line comment: // This is a single line comment


● Multi-line comment: /* comment starts
…………….
Comment ends */
Basic Syntax:

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

Rules of valid identifier:

1. Case-Sensitive: C is case-sensitive, so myVariable and myvariable are considered different identifiers.


2. Start with a Letter or Underscore: The first character of an identifier must be a letter (a-z or A-Z) or an
underscore (_).
3. Consist of Letters, Digits, and Underscores: Subsequent characters can be letters, digits (0-9), or
underscores.
4. No Special Characters: Avoid using special characters like $, @, %, or spaces within identifiers.
5. Avoid Keywords: Don't use reserved keywords (like int, float, if, else, etc.) as identifiers.

Examples of Valid Identifiers: Examples of Invalid Identifiers:

● age ● 123number (starts with a digit)


● _count ● my-variable (contains a hyphen)
● myFunction
● int (keyword)
● total_sum
Data types in C

Data type Size Format Description Example


(Bytes) Specifier

char 1 %c Stores a single character. char c= 'A';

short 2 %hd Stores a short integer short s = 10;

int 4 %d Stores whole numbers (integers). int i = 20;

long 8 %ld Stores a long integer long l = 30;

float 4 %f Stores single-precision floating-point float f = 3.14;


numbers (numbers with decimals)

double 8 %lf Stores double-precision floating-point double d = 2.71828;


numbers (more precise than float).

long 16 %Lf Stores an extended-precision floating-point long double ld =


double number 1.23456789012345;
Constants:
● Variables with fixed values
● Values cannot be modified in the program once they are
defined.

Examples of constants:
const int c=20;

Strings:

● Array of characters ended with a null character (‘\0’)


● Null character indicates the end of the string.
● Always enclosed in double quotes
● A character is enclosed in single quotes 1. Direct Initialization:

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<stdio.h>: It is used to perform input and output operations using


functions scanf() and printf().

#include<string.h>: It is used to perform various functionalities related to string manipulation


like strlen(), strcmp(), strcpy(), size(), etc.

#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:

● Parentheses ( ) (used for function calls, grouping expressions, and casting)


● Braces { } (used to define blocks of code)
● Square brackets [ ](used for array indexing)
● Semicolon ; (used to terminate statements)
● Comma , (used to separate items in a list)
● Dot operator . (used to access members of structures and unions)
● Arrow operator -> (used to access members of structures and unions through pointers)
● Preprocessor directive # (used for instructions to the compiler before compilation)
Operators

● Symbols that trigger an action when applied to C variables and other objects
● The data items on which operators act are called operands

Depending on the number of operands operators can be classified as:

Operators

Unary Binary Ternary

Arithmetic Relational Logical Assignment Bitwise


Operators

Unary Operators: Operate on a single operand.


int a = 5;

● - (Negation): Changes the sign of an operand.


int b = --a; // a is now 4, b is 4
● ++ (Increment): Increases the value of the operand by 1.
○ Prefix: ++x (increments before use) int c = a--; // c is 4, a is now 3

○ Postfix: x++ (increments after use)


● -- (Decrement): Decreases the value of the operand by 1
○ Prefix: --x (decrements before use) int x = 10;
○ Postfix: x-- (decrements after use) int *ptr = &x; // ptr holds address of x
printf("%d",ptr); // prints mem address
● & (Address-of): Returns the memory address of the operand. printf("%d",*ptr); // prints 10
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.

○ % (Modulus): Returns the remainder of the division. Etc

● Ternary Operator: Requires three operands to act upon. int x = 10;


int y = (x > 5) ? 20 : 30; // y will be 20
○ condition ? expression1 : expression2
Arithmetic Instructions

● To perform arithmetic operations between constants and variables.


● Consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =.
● Variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /

For example

float delta, alpha, beta, gamma ;

delta = alpha * beta / gamma + 3.2 * 2 / 5 ;

*, /, -, + are the arithmetic operators.

= is the assignment operator.

delta, alpha, beta, gamma are real variables.


Arithmetic Instructions
Arithmetic Instructions

#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;

printf("Sum: %d\n", sum); // Output: 15


printf("Difference: %d\n", difference); // Output: 5
printf("Product: %d\n", product); // Output: 50
printf("Quotient: %d\n", quotient); // Output: 2
printf("Remainder: %d\n", remainder); // Output: 0

}
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

the following expression:

i=2*3/4+4/4+8-2+5/8
Relational operator

● Used to compare two values or expressions and determine their relationship.


● Result of a relational operation is a boolean value, either true (non-zero) or false (zero).
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

● Used to combine multiple conditions or boolean expressions


● Help determine the overall truth value of a complex expression based on the
truth values of its individual components.

Operator Meaning Example

&& Logical AND (a > 0) && (b < 10)

|| Logical OR ((a > 0) || (b < 0))

! Logical NOT !(a == 0)


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:

int age = 30;

char grade = 'A';

float pi = 3.14159;
Bitwise operator

● Work directly on the individual bits (binary digits: 0 or 1) of an integer data


type
● .Used for low-level operations and can be very efficient for certain tasks.
Bitwise operator

● One’s complement(~): Inverts all the bits of the operand


int num = 10; // Binary: 00001010
int ones_complement = ~num;
● Right shift(>>): Shifts the bits of the first operand to the right by the number of
positions specified by the second operand.
int x = 20; // Binary: 00010100
int y = x >> 2; // Shift 20 two positions to the right
// Result: //
y = 5 (Binary: 00000101)
Bitwise operator

● Left shift(<<): Shifts the bits of the first operand to the left by the number of positions specified by the second
operand.

int x = 5; // Binary: 00000101

int y = x << 2; // Shift 5 two positions to the left

// 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

int b = 25; // Binary: 00011001 printf("b: %d (Binary: %08b)\n", b, b);

int result = a & b; printf("Result of a & b: %d (Binary: %08b)\n", result,


result);
Bitwise operator

● Bitwise OR:Sets a bit to 1 in the result if at least one of the corresponding


bits in the operands is 1.
int a = 12; // Binary: 00001100
int b = 25; // Binary: 00011001
int result = a | b; /// output: 29
● Bitwise XOR:Sets a bit to 1 in the result if the corresponding bits in the
operands are different.
int result = a ^ b; /// output: 21
Conditional Statements in C

● 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.

Main types of conditional statements in C:

1. if Statement:
a. Executes a block of code only if a specified condition is true.

if (condition) {

// Code to be executed if condition is true

}
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) {

// Code to be executed if condition is true

} else {

// Code to be executed if condition is false

}
Conditional Statements in C

3. if-else if-else Statement:

● Allows you to check multiple conditions sequentially.


● If the first condition is true, its corresponding block is executed.
● If the first condition is false, the program checks the next else if condition, and so on.
● If none of the if or else if conditions are true, the else block (if present) is executed.
if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition1 is false and condition2 is true

} else if (condition3) {

// Code to be executed if condition1 and condition2 are false and condition3 is true

} else {

// Code to be executed if none of the above conditions are true

}
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:

● Age: Must be 18 years or older.


● Weight: Must be 50 kilograms or more.
Solution
#include <stdio.h> if (age >= 18)

int main() { if (weight >= 50)

{ { printf("You are eligible to donate


blood.\n"); }
int age, weight;
else {
printf("Enter your age: ");
printf("You are not eligible to donate
scanf("%d", &age); blood. Weight is insufficient.\n"); }
printf("Enter your weight in kg: "); }
scanf("%d", &weight); else { printf("You are not eligible to
donate blood. Age is below 18.\n"); }

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) {

case value1: // Code to be executed if expression == value1

break; //used to terminate a case in the switch statement

case value2: // Code to be executed if expression == value2

break;

// ... more cases ...

default: // Code to be executed if none of the cases match

}
Find grade of a student using switch case
switch (percentage / 10) {

case 6: case 7: case 8: case 9: case 10:


#include<stdio.h>
printf("First Division\n");
void main( )
break;
{
case 5:
int m1, m2, m3, m4, m5, percentage ;
printf("Second Division\n");
printf ( "Enter marks in five subjects " ) ;
break;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
case 4:
percentage = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
printf("Third Division\n");
printf("Percentage: %d\n", percentage);
break;

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

You might also like