1 of 26

Introduction

What is Programming?

Computer programming is a medium for us to communicate with computers, just like we use Hindi or English to communicate with each other. Programming is a way for us to deliver our instructions to the computer.

What is C?

C is a programming language. C is one of the oldest and finest programming languages. C was developed by Dennis Ritchie in 1972.

Uses of C

C is a language that is used to program a wide variety of systems. Some of the uses of C are as follows:

Major parts of Windows, Linux, and other operating systems are written in C.

C is used to write driver programs for devices like Tablets, Printers, etc.

C language is used to program embedded systems where programs need to run faster in limited memory.

C is used to develop games, an area where latency is very important, i.e., a computer has to react quickly to user input.

DGCC, Department of Information Technology

2 of 26

Variables, Constants, and Keywords

  • A variable is a container that stores a ‘value.’ In the kitchen, we have containers storing rice, dal, sugar, etc. Similar to that variable in c stores the value of a constant. Example:
  • a = 3 a is assigned “3”
  • b = 4.7 b is assigned “4.7”
  • c = 'A' c is assigned “A”
  • Rules for naming variables in c:
  • 1. The first character must be an alphabet or underscore(_).
  • 2. No commas or blanks are allowed.
  • 3. No special symbol other than underscore is allowed
  • 4. Variable names are case sensitive

DGCC, Department of Information Technology

3 of 26

Constants

  • An entity whose value doesn’t change is called a constant.
  • Types of constant
  • Primarily there are 3 types of constant:
  • 1. Integer Constant -1,6,7,9
  • 2. Real Constant -322.1,2.5,7.0
  • 3. Character Constant ‘a’,’$’,’@’(must be enclosed within single inverted commas)

DGCC, Department of Information Technology

4 of 26

Keywords

These are reserved words whose meaning is already known to the compiler. There are 32 keywords available in c:

auto double int struct

break long else switch

case return enum typedef

char register extern union

const short float unsigned

continue signed for void

default sizeof goto volatile

do static if while

DGCC, Department of Information Technology

5 of 26

First C program�

#include<stdio.h>

int main() {

printf(“Hello, I am learning C with Mr. Modi”);

return 0;

}

The basic structure of a C program

  • All c programs have to follow a basic structure. A c program starts with the main function and executes instructions presents inside it. Each instruction terminated with a semicolon(;)
  • There are some basic rules which are applicable to all the c programs:
  • Every program's execution starts from the main function.
  • All the statements are terminated with a semi-colon.
  • Instructions are case-sensitive.
  • Instructions are executed in the same order in which they are written.

Comments

  • Comments are used to clarify something about the program in plain language. It is a way for us to add notes to our program. There are two types of comments in c:

Single line comment: //This is a comment.

Multi-line comment : /*This is multi-line comment*/

  • Comments in a C program are not executed and ignored.
  • Compilation and execution
  • A compiler is a computer program that converts a c program into machine language so that it can be easily understood by the computer.
  • A program is written in plain text. This plain text is a combination of instructions in a particular sequence. The compiler performs some basic checks and finally converts the program into an executable.

DGCC, Department of Information Technology

6 of 26

Compilation and execution�

  • A compiler is a computer program that converts a c program into machine language so that it can be easily understood by the computer.
  • A program is written in plain text. This plain text is a combination of instructions in a particular sequence. The compiler performs some basic checks and finally converts the program into an executable.

Library functions

  • C language has a lot of valuable library functions which is used to carry out a certain task; for instance, printf function is used to print values on the screen.
  • printf(“This is %d”,i);
  • // %d for integers
  • // %f for real values
  • // %c for characters

DGCC, Department of Information Technology

7 of 26

Types of variables�

  • Integer variables int a=3;
  • Real variables int a=7.7 (wrong as 7.7 is real) ; float a=7.7;
  • Character variables char a=’B’;
  • Receiving input from the user
  • In order to take input from the user and assign it to a variable, we use scanf function.
  • The syntax for using scanf:
  • scanf(“%d”,&i); // [This & is important]
  • & is the “address of” operator, and it means that the supplied value should be copied to the address which is indicated by variable i.

DGCC, Department of Information Technology

8 of 26

Questions

  • Q1. Write a c program to calculate the area of a rectangle:
  • a) using hardcoded inputs &
  • b) using inputs supplied by the user
  • Q2. Calculate the area of a circle and modify the same program to calculate the volume of a cylinder given its radius and height.
  • Q3. Write a program to convert Celsius (Centigrade degrees temperature to Fahrenheit)
  • Q4. Write a program to calculate simple interest for a set of values representing principle, no of years, and rate of interest.

DGCC, Department of Information Technology

9 of 26

Instructions and Operators:�

  • A C-program is a set of instructions. Just like a recipe - which contains instructions to prepare a particular dish.
  • Types of instructions:
  • 1.Type declaration instruction
  • 2. Arithmetic instruction
  • 3.Control instruction
  • Type of declaration instruction:
  • int a;
  • float b;
  • other variations:
  • int i = 10; int j = i, int a = 2;
  • int j1 = a + j - i;
  • float b = a+3; float a = 1.1; ==>Error! As we are trying to use a before defining it.
  • int a,b,c,d;
  • a=b=c=d=30; ==> Value of a,b,c & d will be 30 each.

DGCC, Department of Information Technology

10 of 26

  • Note:
  • 1.No operator is assumed to be present
  • int i=ab ( Invalid )
  • int i=a*b ( valid )
  • 2.There is no operator to perform exponentiation in c however we can use pow(x,y) from <math.h>(More later).

DGCC, Department of Information Technology

11 of 26

Conditional Instructions�

  • Sometimes we want to watch comedy videos on YouTube if the day is Sunday. Sometimes we order junk food if it is our friend's birthday in the hostel. You might want to buy an umbrella if it's raining and you have the money. You order the meal if dal or your favorite bhindi is listed on the menu.
  • All these are decisions that depend on conditions being met.
  • In ‘C’ language, too, we must be able to execute instructions on a condition(s) being met.
  • Decision-making instructions in C
  • If-else statement
  • Switch statement
  • If-else statement
  • The syntax of an if-else statement in c looks like this:
  • if ( condition to be checked) {
  • Statements-if-condition-true ;
  • }
  • else{
  • statements-if-condition-false ;
  • }
  • Code Example
  • int a=23;
  • if (a>18){
  • printf(“you can drive\n”);
  • }
  • Note that else block is not necessary but optional.

DGCC, Department of Information Technology

12 of 26

Relational Operators in C�

  • Relational operators are used to evaluate conditions (true or false) inside the if statements. Some examples of relational operators are:
  • == equals to
  • >= greater than or equal to
  • > greater than
  • < less than
  • <= less than or equal to
  • != not equal to
  • Important Note: '=' is used for an assignment, whereas '==' is used for an equality check.
  • The condition can be any valid expression. In C, a non-zero value is considered to be true.

DGCC, Department of Information Technology

13 of 26

Operator Precedence�

  • Priority Operator
  • 1st !
  • 2nd *,/,%
  • 3rd +,-
  • 4th <>,<=,>=
  • 5th ==,!=
  • 6th &&
  • 7th ||
  • 8th =

DGCC, Department of Information Technology

14 of 26

Practice Set - if - else

  • What will be the output of this program?
  • int a=10;
  • if(a=11)
  • printf(“I am 11”);
  • else
  • printf(“I am not 11”);
  • Write a program to find out whether a student is pass or fail; if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as input from the user.
  • Calculate income tax paid by an employee to the government as per the slabs mentioned below:
  • Income Slab Tax
  • 2.5L-5.0L 5%
  • 5.0L-10.0L 20%
  • Above 10.0L 30%
  • Note that there is no tax below 2.5L. Take income amount as an input from the user.
  • Write a program to find whether a year entered by the user is a leap year or not. Take the year as input from the user.
  • Write a program to determine whether a character entered by the user is lowercase or not.
  • Write a program to find the greatest of four numbers entered by the user

DGCC, Department of Information Technology

15 of 26

Loop Control Instruction

  • Why loops?
  • Sometimes we want our programs to execute a few sets of instructions over and over again, for eg. Printing 1 to 100, first 100 even numbers, etc.
  • Hence loops make it easy for a programmer to tell the computer that a given set of instructions must be executed repeatedly.
  • Types of Loops: Primarily, there are three types of loop in c language:
  • 1.While loop
  • 2.do-while loop
  • 3.for loop
  • We will look into this one by one
  • While Loop
  • While(condition is true) {
  • // Code // The block keeps executing as long as the condition is true
  • // Code
  • }
  • An example:
  • int i=0;
  • while (i<10){
  • printf(“The value of i is %d”,i); i++;
  • }
  • Note:
  • If the condition never becomes false, the while loop keeps getting executed. Such a loop is known as an infinite loop.
  • Quick Quiz: Write a program to print natural numbers from 10 to 20 when the initial loop counter i is initialized to 0.
  • The loop counter need not be int, it can be a float as well.

DGCC, Department of Information Technology

16 of 26

Increment and decrement operators�

  • i++ (i is increased by 1)
  • i-- (i is decreased by 1)
  • printf(“—i=%d”,--i);
  • This first decrements i and then prints it
  • printf(“i--=%d”,i--);
  • This first prints i and then decrements it
  • +++ operators does not exists => Important
  • += is compound assignment operator just like -=, *=, /= & %= =>Also important

DGCC, Department of Information Technology

17 of 26

Do-while loop:�

  • The syntax of do-while loop looks like this:
  • do {
  • //code;
  • //code;
  • }while(condition)
  • Do-while loop works very similar to while loop
  • While -> checks the condition & then executes the code
  • Do-while -> executes the code & then checks the condition
  • **do-while loop = while loop which executes at least once

DGCC, Department of Information Technology

18 of 26

For Loop�

  • The syntax of for loop looks like this:
  • for( initialize; test; increment or decrement)
  • {
  • //code;
  • //code;
  • }
  • Initialize -> setting a lop counter to an initial value
  • Test -> checking a condition
  • Increment -> updating the loop counter
  • An example:
  • for(i=0;i<3;i++)
  • {
  • printf(“%d”,i);
  • printf(“\n”);
  • }
  • Output:
  • 0
  • 1
  • 2
  • Quick Quiz: Write a program to print first n natural numbers using for loop.

DGCC, Department of Information Technology

19 of 26

A case of Decrementing for loop�

  1. for(i=5; i; i--)
  2. printf(“%d\n”,i);
  3. This for loop will keep on running until i becomes 0.
  4. The loop runs in the following steps:
  5. i is initialized to 5
  6. The condition “i” (0 or none) is tested
  7. The code is executed
  8. i is decremented
  9. Condition i is checked, and the code is executed if it's not 0.
  10. & so on until i is non 0.
  11. Quick Quiz: Write a program to print n natural numbers in reverse order.

DGCC, Department of Information Technology

20 of 26

The Break Statement in C�

  • The break statement is used to exit the loop irrespective of whether the condition is true or false. Whenever a “break” is encountered inside the loop, the controls are sent outside the loop.
  • Let us see with an example:
  • for (i=0; i<1000; i++){
  • printf("%d\n",i);
  • if (i==5){
  • break;
  • }
  • }
  • Output: 0, 1, 2, 3, 4, 5 and not 0 to 100

DGCC, Department of Information Technology

21 of 26

The continue statement in c�

  • The continue statement in c is used to immediately move to the next of the loop. The control is taken to the next iteration, thus skipping everything below continue inside the loop for that iteration.
  • Let us look at an example:
  • int skip=5;
  • int i=0;
  • while(i<10){
  • if(i != skip)
  • continue;
  • else
  • printf(%d”,i);
  • }
  • Output: 5 and not 0................9
  • Notes:
  • 1. Sometimes, the name of the variable might not indicate the behavior of the program.
  • 2. Break statement completely exits the loop
  • 3. Continue statement skips the particular iteration of the loop

DGCC, Department of Information Technology

22 of 26

Practice Set -do -while

  • Write a program to print the multiplication table of a given number n.
  • Write a program to print a multiplication table of 10 in reversed order
  • A do-while loop is executed:
  • At least once
  • At least twice
  • At most once
  • 4. What can be done using one type of loop can also be done using the other two types of loops – True or False.
  • 5. Write a program to sum the first ten natural numbers using a while loop.
  • 6. Write a program to implement program 5 using for and do-while loop.
  • 7. Write a program to calculate the sum of the numbers occurring in the multiplication table of 8.(Consider 8x1 to 8x10)
  • 8. Write a program to calculate the factorial of a given number using for loop.
  • 9. Repeat 8 using a while loop.
  • 10. Write a program to check whether a given number is prime or not using loops.
  • 11. Implement 10 using other types of loops.

DGCC, Department of Information Technology

23 of 26

Number Guessing Game�

  • Project 1: Problem: This is going to be fun!! We will write a program that generates a random number and asks the player to guess it. If the player’s guess is higher than the actual number, the program displays “Lower number please.” Similarly, if the user’s guess is too low, the program prints “Higher number please.”
  • When the user guesses the correct number, the program displays the number of guesses the player used to arrive at the number.
  • Hints:
  • Use loops
  • Use a random number generator.
  • Code:
  • #include<stdio.h>
  • #include<stdlib.h>
  • #include<time.h>
  • int main(){
  • int number, guess, nguesses=1;
  • srand(time(0));
  • number = rand()%100 + 1; // Generates a random number between 1 and 100
  • // printf("The number is %d\n", number);
  • // Keep running the loop until the number is guessed
  • do{
  • printf("Guess the number between 1 to 100\n");
  • scanf("%d", &guess);
  • if(guess>number){
  • printf("Lower number please!\n");
  • }
  • else if(guess<number){
  • printf("Higher number please!\n");
  • }
  • else{
  • printf("You guessed it in %d attempts\n", nguesses);
  • }
  • nguesses++;
  • }while(guess!=number);
  • return 0;
  • }

DGCC, Department of Information Technology

24 of 26

Functions and Recursions

  • What is a function?
  • A function is a block of code that performs a particular task. A function can be reused by the programmer in a given program any number of times.
  • Example and syntax of a function:
  • #include<stdio.h>
  • void display(); // Function prototype
  • int main(){
  • int a;
  • display(); // Function call
  • return(0);
  • }
  • void display(){ // Function definition
  • printf(“Hi I am display”);
  • }
  • Function prototype:
  • Function prototype is a way to tell the compiler about the function we are going to define in the program.
  • Here void indicates that the function returns nothing.
  • Function call:
  • Function call is a way to tell the compiler to execute the function body at the time the call is made.
  • Note that the program execution starts from the main function in the sequence the instructions are written.
  • Function definition:
  • This part contains the exact set of instructions that are executed during the function call. When a function is called from main(), the main function falls asleep and gets temporarily suspended. During this time, the control goes to the function being called when the function body is done executing main() resumes.
  • Quick Quiz: Write a program with three functions,
  • Good morning function which prints "Good Morning."
  • Good afternoon function which prints "Good Afternoon."
  • Good night function, which prints "Good night."
  • main() should call all of these in order 1 - 2 - 3.

DGCC, Department of Information Technology

25 of 26

Important Points:�

  • Execution of a c program starts from main()
  • A c program can have more than one function
  • Every function gets called directly or indirectly from main()
  • There are two types of functions in c. Let's talk about them.
  • Types of Functions:
  • Library functions: Commonly required functions grouped together in a library file on disk.
  • User-defined functions: These are the functions declared and defined by the user.
  • Why use functions?
  • To avoid rewriting the same logic again and again
  • To keep track of what we are doing in a program
  • To test and check logic independently
  • Passing values to functions:
  • We can pass values to a function and can get a value in return from a function
  • int sum(int a, int b)
  • The above prototype means that sum is a function which takes values a(of type int) and b(of type int) and returns a value of type int
  • Function definition of sum can be:
  • int sum(int a, int b){
  • int c; => a and b are parameters
  • c=a+b;
  • return c;
  • }
  • Now we can call sum(2,3) [here 2 and 3 are arguments]; from main to get 5 in return.
  • int d=sum(2,3); => d becomes 5
  • Note:
  • 1. Parameters are the values or variable placeholders in the function definition. Ex: a & b
  • 2. Arguments are the actual values passed to the function to make a call. Ex: 2 & 3
  • 3. A function can return only one value at a time.
  • 4. If the passed variable is changed inside the function, the function call doesn’t change the value in the calling function.

DGCC, Department of Information Technology

26 of 26

Thank You

DGCC, Department of Information Technology