Introduction to C Programming

Preview:

Citation preview

Introduction to C Programming

PresentationBy Varun Uday

varunuday@gmail.com+919947772401

Hi-Tech Computer School

Algorithm – It is a problem solving technique which follows a step by step analysis of solving a problem with a finite time. It helps to find a solution to a problem in a desired form. An algorithm should be designed such that it should be precise and terminate in an almost finite steps and period.

Flowchart – It is a graphical representation of an algorithm/program. It is more helpful in the sense that ,easy to understand if represented in a diagrammatic form. This has the following shapes to be followed in bringing a solution:- Oval, Parallelogram, Rectangle ,Diamond, Annotation, Connectors etc.

Relationship with a program It helps to resolve any type of problems by its step by step approach to

the solution of the respective program.

Algorithm and Flowchart

The First Step must be Start Final Step must be Stop It must be entered in a sequential format and not particular that it

must be in number or any other form.

EXAMPLE : // To prepare a cup of Tea Start Ingredients required – water ,milk , tea powder, sugar etc. Boil mixture Tea is ready Stop

Rules and Regulation

Annotation

Basic Shapes

Start/Stop Processing

FLOW

Input / Output

connector

Decision Box

Example Start

water,milk,tea powder, sugar.

Boil mixture

Tea is ready

stop

A

A

Combined BCPL and B to new one by Dennis Ritchie and named as C in 1972

BCPL –Basic Combined Programming Language by Martin Richard in 1967

B – by Ken Thompson in 1970

In 1978 – K & R C – Book published by Kernighan and Ritchie.

In 1989 – approved by ANSI – ANSI C

In 1990 – approved by ISO – ISO C

History Of C

Structured

High-Level

Machine Independent

Robust

Rich set of built in functions and operators

Free-form language

Ability to extend itself

Highly portable

Includes library files

Characteristics of language

There basically two types of languages – a) HLL b) LLL. Sometimes there it may consider a Middle Level Language also likewise it may be three. Normally under Low Level Language, we can list Assembly Level Language and Machine Level Language. Normally under Low Level Language, we can list Assembly Level Language and Machine Level Language. Low-level programming languages are sometimes divided into two categories: first generation, and second generation. By a HLL – Only understandable by human and carries a machine- independent behavior C , C++, java etc are examples of HLL.

Language Processors Compiler – HLL to Machine L L Interpreter – HLL to Machine L L Assembler – Assembly to Machine

Types Of Errors Syntax – If not following the rules put forward by the program for eg. Missing of

brackets, commas, termination of brackets incorrectly etc Logical – not getting the desired output, Program may one and output may be

another. Run-time – Invalid data entry or other exceptional errors.

High Level &Low Level Languages

Compiler – HLL to MLL. Input file is generally called source file and the output file is generally called Object file. The compilation process is time consuming as each HLL command has to be converted into several Machine language commands. Once the translation is over the object file is saved and can be used for efficient repeated execution for the program. The compiler is best when a program line has to be best executed repeatedly for a very large data or in future use. It can only check syntax errors. The Compiler is not involved if an object file is created until it is modified.

Interpreter – HLL to MLL. It looks at each source language line one by one, breaks it into grammatical parts and executes the action required for the line like ADD or PRINT etc. If the same action has to be carried out for say 5 lakh students then each time the interpreter has to look fresh at the source line and break it into parts before it can execute the action. Interpreters execute the programming lines directly and therefore have to take care of run time errors

Compiler & Interpreter

First Generation Languages

The first-generation programming language, or 1GL ,is machine code. It is the only language a microprocessor can process directly without a previous transformation. Currently, programmers almost never write programs directly in machine code, because it requires attention to numerous details which a high-level language would handle automatically, and also requires memorizing or looking up numerical codes for every instruction that is used. For this reason, second generation programming languages provide one abstraction level on top of the machine code.Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number:8B542408 83FA0077 06B80000 0000C383 FA027706 B8010000 00C353BB 01000000 B9010000 008D0419 83FA0376 078BD98B C84AEBF1 5BC3

Second Generation Languages The second-generation programming language, or 2GL, is 

assembly language. It is considered a second-generation language because while it is not a microprocessor's native language, an assembly language programmer must still understand the microprocessor's unique architecture (such as its registers and instructions). These simple instructions are then assembled directly into machine code. The assembly code can also be abstracted to another layer in a similar manner as machine code is abstracted into assembly code. Example: The same Fibonacci number calculator as above, but in x86 assembly language using MASM syntax: fib: mov edx,[esp+8] cmp edx, 0 ja @f mov eax, 0 ret @@: cmp edx, 2 ja @fmov eax, 1 ret @@: push ebx mov ebx, 1 mov ecx, 1 @@: leaeax, [ebx+ecx] cmp edx, 3 jbe @f mov ebx, ecx mov ecx, eax dec edx jmp @b @@: pop ebx ret.

Consists Of Three significant parts1. Header file2. Function3. Function body

Header file Pre-processor Directive - #include Library File – stdio.hHeader – file #include<stdio.h> ,#define M 10

Basic Structure Of C

Execution part of a program ex. main()Different types of Main function are main(void) ,void main(void), int

main(void)void main() ,int main(), main().Function BodyContents included after function is declared{

body }

Function

#include<stdio.h>void main(){}Practical Implementation#include<stdio.h>void main(){clrscr();getch();} clrscr(); - clearing previous output getch(); - empty statement used for retrieving output

Syntax Of C

In windows we make use for turbo C/ turbo C++, Borland C++, zortech C++ etc

In Linux we use a text editor, where already a compiler is there, output is got in

terminal.Ex vi/ed filename.c writing as C pgm cc filename.c compiling C /.a.out execution

Program StatementsEvery Statement in a program should terminate with a semicolon(;)Input/Output Statements are Scanf(); , Printf(); respectivelyScanf – for accepting values from keyboard.for Integer values - %d, Fractional-%f character - %cPrintf – for showing the output in the prompt

Execution

Execution in Turbo –

• Take My Computer

Select C Drive from My computer

Open TC folder from C Drive

C:\TC

Double click on TC.EXE

Turbo C++ will appear

Right click on TC.EXE then select send to Desktop –short cut to desktop

Turbo C++ short cut icon can see on the screen

Double Click from the desktop

on Turbo C++ -Turbo will open the application

Select the file menu and choose the submenu - new

Display of prompt after compilation and running

Directory making command-md directoryname(Eg:-md akhila )

md directory name and press enter

Directory will created. The command C:\TC> Line will Appear

For entering into the directory-command is cd directory name(Eg:cd akhila) then press enter

For backtrackin-cd.. (control will go out from the

directry Eg-C:/TC ) The command Exit is for exiting

the command prompt

Turbo screen

Write C program on this screen and save it(FILE-Save)

Then Save File As window will appear write your program name.extension (Eg:first.c)

After saving the program the path looks like(AKHILA\FIRST.C)

Take Compile and followed by Run Command Prompt with desired output will appear

#include<stdio.h>void main(){clrscr();printf(“hello welcome to C++”);getch();}OutPut of the pgm

In Prompt in Windows as

hello welcome to C

First Program in C

Smallest Individual unit of a program can be said as a Token. Tokens can be classified as follows Keywords, Identifiers ,Literals, Separators, Operators .

Keywords -Any part of the program which can be commented by a name Eg int, float, for.

Identifier-Which keeps an identity or it can be commented as variable which can be used to store a value. They are programmer designed tokens used for naming variables etc. Eg. int month, char vowel, class student etc.

Literals-It can be just digits or letters etc which may add to the program. Constant value stored in variables.Ex 1,2 etc or a, b etc or any special types.

Separators-It can be anything which makes a difference between the two Eg. punctuators, comma, periods etc “ , .(),{},[] etc

Operators-Which uses the program to functions with Suitable elements such as +,-,\,* etc.Operators can be classified as Arithmetic Operators, Relational Operators Logical Operators, Assignment Operators, Bitwise Operators, Conditional Operators, Increment and Decrement Operators.

Tokens

Arithmetic Operators - +,-,*,/ etc .Are also called as unary operators . a - b, a + b , a/b , a % b .

Relational Operators - <,<=,>,>=,==,!=.Checking expressions for eg. a>b etc

Logical Operators - Logical AND,OR,NOT - &&,||,! . a > b && x = = 10 ,a < m || a < n ,! (x >= y) . Assignment Operators - V OP=Exp ;V=V op(exp); Eg =(equals) C =A+B; Increment and Decrement - ++,- - etc Ex. M++,C- - e We have here post and pre but we normally take post. Bitwise Operators - Only used in specific Area

&,^,~,<<,>>,<<< etc Conditional Operators - Expression Format is Exp1?Exp2:Exp3 .Eg. A>B?A:B Special Operators -::,white spaces etc,\n,\t etc./*….*/

Operators

Operator Symbol Form Operation

left shift << x << y l bits in x shifted left y bits

right shift >> x >> y all bits in x shifted right y bits

bitwise NOT ~ ~x all bits in x flipped

bitwise AND & x & y each bit in x AND each bit in y

bitwise OR | x | y each bit in x OR each bit in y

bitwise XOR ^ x ^ y each bit in x XOR each bit in y

#include<stdio.h>#include <conio.h>   void main() {     int x = 5; clrscr();printf(“%d”, ++x); /* x is incremented before being passed to printf

so the value 6 */getch();}Out put :- 6

Program for Pre increment

#include<stdio.h>#include <conio.h>   void main() {     int x = 5; clrscr();printf(“%d”,  x++);/* x is passed to printf and then incremented  getch();}Out put-5

Program for post increment

#include<stdio.h>#include <conio.h>   void main() {     int x = 5; clrscr();      printf(“%d”, ++x); printf(“%d”,  x++);printf(“%d”,  );      getch();} Outputx=6 In the first printf statement x is incremented before being

passed to printf ,so the is value 6 . x=6 in the second x is passed to printf(so 6 is output) and then incremented

x=7 the 3rd printf statement just shows that post increment following the previous statement

Example for Post &Pre

Variables -Variables in C are memory locations that are given names and can be assigned values. We use variables to store data in memory for later use. There are 2 basic kinds of variables in C which are numeric and character.

Numeric variables - Numeric variables can either be integer values or they can be Real values. Integer values are whole numbers without a fraction part or decimal point in them. Real numbers can have a decimal point in them.

Character variables - Character variables are letters of the alphabet as well as all characters on the ASCII chart and even the numbers 0 - 9. Characters must always be put between single quotes. A number put between single quotes is not the same thing

as a number without them.

Variables

To declare a variable we first put the type of variable and then give the variable a name. The following is a table of the names of the types of variables as well as their ranges:

Name Type Range Int Numeric - Integer-32 768 to 32 767 Short Numeric - Integer-32 768 to 32 767 Long Numeric - Integer-2 147 483 648 to 2 147 483 647 Float Numeric – Real 1.2 X 10-38 to 3.4 X 1038 Double Numeric – Real 2.2 X 10-308 to 1.8 X 10308 Char Character All ASCII characters

Variables Contnd..

You can name a variable anything you like as long as it includes only letters, numbers or underscores and does not start with a number. It is a good idea to keep your variable names less than 32 characters long to save time on typing them out and for compiler compatibility reasons. Variables must always be declared at the top before any other commands are used. Now let's declare an integer variable called a and a character variable called b.

int main(){   int a;   char b;   return 0;}

Variable Contnd..

 Variables with BLOCK SCOPE (variables declared in a block,i.e. local variables) are the least accessible, as they are visible between an opening curly bracket and a closing one. Variables with FUNCTION SCOPE (goto labels in this case) are the next least accessible, as they are visible in a whole function.Variables with FILE SCOPE(global variables with the static specifier)are the second most accessible, as they are visible in the whole file. Finally, variables with PROGRAM SCOPE (variables declared outside any blocks, i.e. global variables) are always accessible throughout the program.

 

Scope Of variables

The difference between variables and constants is that variables can change their value at any time but constants can never change their value. Constants can be useful for items such as Pi or the charge on an electron. Using constants can stop you from changing the value of an item by mistake. Constants refers to fixed values that cannot be changed during the execution of a program. Constants can be of Numeric and Character Constants.

Numeric - Integer – Refers to a sequence of digits. Three types of integers decimal ,octal , hexadecimal etc .Real – Numbers represented by fractional parts like 17.85.

Character - Character – Single character only ‘5’, ‘X’ ‘ ’ ‘;’etc. The character ‘5’ is not same as number 5.String – is a sequence of characters enclosed between double quotes. The character may be digits , numbers special characters and blank spaces.

Constants

Primary User defined – Union, Enumeration, Structure etc Derived (Non-Primitive) – Arrays , Functions , Classes etc Empty – void

Primary/Fundamental / Primitive Data TypesNumeric and Non NumericNumeric – Integer and Floating Point typesNon- numeric – Character Integer – int , short , long int – 4 bytes ,short – 2 bytes, long – 8 bytes Floating Point – float , double float - 4 bytes ,double – 8 bytes Character – char(2 bytes)

Data Types

Data Types

Program to Initialize a value with and with out giving input.

Program to Initialize two values.

Program to find sum, difference, product, Division and remainder etc

Programs in C

#include<stdio.h>#include<conio.h>void main(){ int a=12;clrscr();printf(“ The value of a is : %d” , a);getch();}

Programs in C contnd..

#include<stdio.h>#include<conio.h>void main(){ int a=12,b=20;clrscr();printf(“ The values of a and b is : %d, %d” , a, b);getch();}

Programs in C contnd..

#include<stdio.h>#include<conio.h>void main(){ int a; int b; clrscr(); printf(“Enter the values”);scanf(“%d%d”,&a,&b);printf(“ The sum of a and b: %d” , a+b); getch();}

Programs in C contnd..

To calculate the Area ,Perimeter, Circumference and Volume of the Rectangle, Square, Triangle , Circle, Cone etc..

To calculate the total marks , average and percentage of a student To calculate the net salary of an employee To calculate the total monthly expense in your family. To compare two numbers which is greater W.A.P to swap two numbers

Exercises 1

Control Statements

Selection Statement – IF , SWITCH

Looping Statement – FOR, WHILE, DO- WHILE

Jump statement – Go To, Break, Continue ,Return

IF Statement There are mainly four Typesa) Simple Ifb) If – elsec) else – If ladderd) Nested If

Simple If – It only contains a if and followed by an expression. The Syntax of If can be

if(expression){Statement;}Statement;

If – else statement It contains an if with expression followed by else.

if(expression){Statement;}else{Statement;}

Example #include<stdio.h> void main() { int a=10,b=20; if(a>b) printf(“a is greater”); printf(“b is smaller”); }

else – if statement

It contains if ,else if and an else.

if(expression)

Statement;

else if(expression)

Statement;

else

Statement;

Nested If statement

if(expression) { if(expression) {statement;} else { statement;}}else { if (expression) { statement; } else{ statement;}}

Switch statement

It contains an exp/identifier followed by case and break, finally default.

switch(expression){case 1:Statement; break;case 2:Statement; break;default :Statement; break;}

For statementThis statement which executes several times with an increment

depending on the conditions. The expression format is :for (i=0; i<n; i++) here n can be any valueIf n = 10; then output will be from 0 to 10.

While statement It is also a several time executing statement depending on the

condition . The expression format is :while (n>0) {n++;}

Do while statementIt is also a several time executing statement depending on the

condition, but here do has more importance as it may transfer the part after the do is executed then to while

do { b=1;} while (b>0);b++;

Jump statementsThese statements cannot have a specific purpose but they execute

along with other control statements such as selection, loop etc. eg. break , continue, return, go to .Sample Program #include <stdio.h>

int main(void) {  int  i = 1;again:  printf("%d ", i);  i++;  if(i<10)       goto again;  return 0;}

Continue & Break statements #include <stdio.h>

void main() {  clrscr();  int n;  do {     printf(" \nEnter the number :");    scanf("%d", &n);    if (n < 0) {      break;    }    if (n >10) {      printf("Skip the value\n");      continue;    }    printf("The number is: %d", n);  } while (n!= 0);}

Exercises 2 W.A.P to compare the numbers W.A.P to check whether vowel or not. W.A.P to declare the result of a student depending upon marks

obtained declare the grade. W.A.P to check whether prime number or not. W.A.P to reverse a number W.A.P to check palindrome or not W.A.P to print asterisk graph W.A.P to print Floyd’s triangle W.A.P to check composite or not W.A.P to Armstrong number or not W.A.P to calculate Fibonacci series W.A.P to calculate the factorial W.A.P to print in pyramid shape

Exercises 2 contnd.. W.A.P to calculate the sum of digits W.A.P to generate a multiplication table W.A.P to add first n natural numbers W.A.P to condense a number into single digit WAP to check whether Leap year or not and to print leap years

from 1901 to 2100 W.A.P to print prime number below a range W.A.P to print even number below a range W.A.P to print odd number below a range W.A.P to print composite number below a range

Arrays An array is a collective name given to a group of similar

quantities. These similar elements can be all integers, or all floats or all characters etc. Each member in the group is referred to by its position in the group. The array of characters are called as String and the array of integers and floats are called simply an Array. All elements of any given array must be of the same type. The number in [] is called ‘dimension’ of the array. The first element in the array is numbered 0,so that the last element is 1 less than the size of the array. Before using an array its type and dimension must be declared .All array elements are always stored in contiguous memory locations. An array is also called a subscripted variables. An array can have two or more dimensions . ex. .Matrix. Array is an example of a derived data type so it is be declared along with fundamental data type. This can be shown as int a[10] or float a[20] or char[50] as follows. If a two dimensional declaration it can be as int a[10][10].In this the first subscript represent row and second points to column. A[10] actually means a[0],a[1],a[2]….a[9].Here we have to increment its position one after the other. So we make use of looping statements.

Initialiazation of Array#include<stdio.h>#include<conio.h>void main(){ int a[10],y,i;clrscr();printf(“ enter the dimension”); scanf(“%d”,y);Printf(“enter the elements of array”);for(i=0;i<y;i++) scanf(“%d”,a[i]); printf(“array”); for(i=0;i<y;i++) printf(“%d”,a[i]);getch(); }

Matrix – 2 Dimensional Array Matrix is a representation such that there are rows and columns.

Matrix operations such as Addition and Subtraction can only done with those matrices which are in the same order. The order of a matrix is nothing but no. of rows and no. of columns. Matrix multiplication is done such that order of matrices should be such that column of the first matrix = row of the second matrix.

Matrix Operations are Addition Subtraction Multiplication Division is not possible.

Matrix Representation

If order is 2x2(pronounced as 2 by 2)

1 2

3 4

Initialiazation of a Matrix#include<stdio.h>#include<conio.h>void main(){ int a[10][10],y,z,i,j;clrscr();printf(“ enter the order of matrix”); scanf(“%d%d”,y,z);printf(“enter the elements of array”);for(i=0;i<y;i++) for(j=0;j<z;j++)scanf(“%d”,a[i][j]); printf(“matrix”); for(i=0;i<y;i++) for(j=0;j<z;j++)printf(“%d”,a[i][j]);getch(); }

Exercise 3W.A.P to initialize two different arrays.W.A.P to reverse an array.W.A.P to find the biggest and lowest element of an array & find the

second largest numberW.A.P to swap two arrays.W.A.P to delete the duplicate elements .W.A.P to delete an element of array.W.A.P is to find sum of elements of array.W.A.P for Fibonacci series using arrays. W.A.P to initialize a two dimensional arrayW.A.P to add and sub two matrices.W.A.P to multiply to matrices.W.A.P to check whether matrix is singular.W.A.P to find the sum of diagonal elements.W.A.P to find the transpose of a matrix

Recommended