Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability.

Slides:



Advertisements
Similar presentations
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Dynamic memory allocation
C Language.
Files in C Rohit Khokher.
Programming Languages and Paradigms The C Programming Language.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Chapter 10.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Pointers Applications
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Basic Elements of C++ Chapter 2.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
20/03/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 File Handling in C Lecture 17c 20/3/01.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Introduction to Programming
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Files A collection of related data treated as a unit. Two types Text
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Chapter Topics The Basics of a C++ Program Data Types
A bit of C programming Lecture 3 Uli Raich.
Chapter 2 - Introduction to C Programming
C Programming Tutorial – Part I
Basic Elements of C++.
C Fundamentals & Pointers
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Short Overview Lembit Jürimägi.
Chapter 2 - Introduction to C Programming
Basic Elements of C++ Chapter 2.
11/10/2018.
Chapter 14 - Advanced C Topics
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
File Handling in C.
The C Language: Intro.
C – Programming Language
Programming Languages and Paradigms
Variables in C Topics Naming Variables Declaring Variables
C Language B. DHIVYA 17PCA140 II MCA.
Introduction to C Programming
Presentation transcript:

Fundamentals and History of C  C is developed by Dennis Ritchie  C is a structured programming language  C supports functions that enables easy maintainability of code, by breaking large file into smaller modules  Comments in C provides easy readability  C is a powerful language

PROGRAM STRCTURE IN C #include void main() { --other statements }

HEADER FILES The files that are specified in the include section is called as header file These are precompiled files that has some functions defined in them We can call those functions in our program by supplying parameters Header file is given an extension.h C Source file is given an extension.c

MAIN FUNCTION This is the entry point of a program When a file is executed, the start point is the main function From main function the flow goes as per the programmers choice. There may or may not be other functions written by user in a program Main function is compulsory for any c program

Sample program #include int main() { printf(“Hello”); return 0; } This program prints Hello on the screen when we execute it

HOW TO RUN C PROGRAM Type a program Save it Compile the program – This will generate an exe file (executable) Run the program (Actually the exe created out of compilation will run and not the.c file) In different compiler we have different option for compiling and running. We give only the concepts.

Points to remember Case Sensitive Case matters in C. A is not a Add plenty of comments (/* */ or //) Good layout, not: main() {printf("Hello World\n");} Use meaningful variable names Initialize your variables Use parentheses to avoid confusion: a=( ) * ( ) / 2.0

DATA TYPES Primitive data types int, float, double, char Aggregate data types Arrays come under this category Arrays can contain collection of int or float or char or double data User defined data types Structures and enum fall under this category.

VARIABLES Variables are data that will keep on changing Declaration > >; int a; Definition >= >; a=10; Usage > a=a+1;//increments the value of a by 1

RULES FOR VARIBLE NAME Should not be a reserved word like int etc.. Should start with a letter or an underscore(_) Can contain letters, numbers or underscore. No other special characters are allowed including space Variable names are case sensitive A and a are different.

INPUT & OUTPUT Input scanf(“%d”,&a); Gets an integer value from the user and stores it under the name “a” Output printf(“%d”,a) Prints the value present in variable a on the screen

OPERATORS Arithmetic (+,-,*,/,%) Relational (, =,==,!=) Logical (&&,||,!) Bitwise (&,|) Assignment (=) Compound assignment(+=,*=,-=,/=,%=,&=,|=) Shift (right shift >>, left shift <<)

OPERATORS(Contd.) Increment and Decrement Operators ++ Increment operator -- Decrement Operator k++ or k-- (Post-increment/decrement) k = 5; x = k++; // sets x to 5, then increments k to 6

(contd.) ++k or --k (Pre-increment/decrement) k = 5; x = ++k; // increments k to 6 and then sets to the resulting value, i.e., to 6

CONTROL CONSTRUCTS

Conditional Statements if (condition) { stmt 1;//Executes if Condition is true } else { stmt 2;//Executes if condition is false }

SWITCH & BREAK switch(var) { case 1://if var=1 this case executes stmt; break; case 2://if var=2 this case executes stmt; break; default: //if var is something else this will execute stmt; }

LOOPS

FOR LOOP The syntax of for loop is for(initialisation;condition checking;increment) { set of statements } Eg: Program to print Hello 10 times for(I=0;I<10;I++) { printf(“Hello”); }

WHILE LOOP The syntax for while loop while(condn) { statements; } Eg: a=10; while(a != 0)Output: { printf(“%d”,a); a- -; }

DO WHILE LOOP The syntax of do while loop do { set of statements }while(condn); Eg: i=10;Output: do { printf(“%d”,i); i--; }while(i!=0)

ARRAYS

Arrays are collection of data that belong to similar data type Arrays are collection of homogeneous data Array elements can be accessed by its position in the array called as index

Contd. Array index starts with zero The last index in an array is num – 1 where num is the no of elements in a array int a[5] is an array that stores 5 integers a[0] is the first element where as a[4] is the fifth element We can also have arrays with more than one dimension float a[5][5] is a two dimensional array. It can store 5x5 = 25 floating point numbers The bounds are a[0][0] to a[4][4]

String functions strlen(str) – To find length of string str strrev(str) – Reverses the string str as rts strcat(str1,str2) – Appends str2 to str1 and returns str1 strcpy(st1,st2) – copies the content of st2 to st1 strcmp(s1,s2) – Compares the two string s1 and s2 strcmpi(s1,s2) – Case insensitive comparison of strings

Function Syntax of function Declaration section > funname(parameter list); Definition section > funname(parameter list) { body of the function } Function Call Funname(parameter);

Example #include void fun(int a);//declaration int main() { fun(10);//Call } void fun(int x)//definition { printf(“%d”,x); }

ACTUAL & FORMAL PARAMETERS Actual parameters are those that are used during a function call Formal parameters are those that are used in function definition and function declaration

Call by value Calling a function with parameters passed as values int a=10;void fun(int a) fun(a);{ defn; } Here fun(a) is a call by value. Any modification done with in the function is local to it and will not be effected outside the function

Call By Reference Calling a function by passing pointers as parameters (address of variables is passed instead of variables) int a=1;void fun(int *x) fun(&a);{ defn; } Any modification done to variable a will effect outside the function also

Explanation a and x are referring to same location. So value will be over written.

Explanation

Conclusion Call by value => copying value of variable in another variable. So any change made in the copy will not affect the original location. Call by reference => Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.

Structures Structures are user defined data types It is a collection of heterogeneous data It can have integer, float, double or character data in it We can also have array of structures struct > { members; }element; We can access element.members;

Example struct Person { int id; char name[5]; }P1; P1.id = 1; P1.name = “vasu”;

typedef statement User Defined Data Types The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; makes the name Length a synonym (or alias) for the data type int.

(contd.) The data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used: Length a, b, len ; Length numbers[10] ;

UNION

Union has members of different data types, but can hold data of only one member at a time. The different members share the same memory location. The total memory allocated to the union is equal to the maximum size of the member.

EXAMPLE #include union marks { float percent; char grade; }; int main ( ) { union marks student1; student1.percent = 98.5; printf( "Marks are %f address is %16lu\n", student1.perc ent, &student1.percent); student1.grade = 'A'; printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade); }

ENUM

(ENUMERATED DATA TYPE) Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name {name_0, …, name_n} ; The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n.

(contd.) As an example, the statement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2.

POINTER Pointer is a special variable that stores address of another variable Addresses are integers. Hence pointer stores integer data Size of pointer = size of int Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip;

Pointers(Contd.) Pointers that store address of a double, char and float are called as double pointer, character pointer and float pointer respectively. char *cp float *fp double *dp; Assigning value to a pointer int *ip = &a; //a is an int already declared

Example int a; a=10;//a stores 10 int *ip; ip = &a;//ip stores address of a (say 1000) ip:fetches 1000 *ip : fetches 10 * Is called as dereferencing operator

Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.

malloc() A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. Example: x=(int*)malloc(100*sizeof(int));

Contd….. On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

Calloc Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size);

Contd…… The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

free() Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. free(ptr); ptr is a pointer that has been created by using malloc or calloc

realloc The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize);

FILE HANDLING

Introduction Files are places where data can be stored permanently. Some programs expect the same set of data to be fed as input every time it is run. Cumbersome. Better if the data are kept in a file, and the program reads from the file. Programs generating large volumes of output. Difficult to view on the screen. Better to store them in a file for later viewing/ processing

Basic File Operations Opening a file Reading data from a file Writing data to a file Closing a file

Opening a File A file must be “opened” before it can be used. FILE *fp; : fp = fopen (filename, mode); fp is declared as a pointer to the data type FILE. filename is a string - specifies the name of the file. fopen returns a pointer to the file which is used in all subsequent file operations. mode is a string which specifies the purpose of opening the file: “r” :: open the file for reading only “w” :: open the file for writing only “a” :: open the file for appending data to it

Closing a File After all operations on a file have been completed, it must be closed. Ensures that all file data stored in memory buffers are properly written to the file. General format: fclose (file_pointer) ; FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;

Read/Write Operations on Files The simplest file input-output (I/O) function are getc and putc. getc is used to read a character from a file and return it. char ch; FILE *fp; ….. ch = getc (fp) ; getc will return an end-of-file marker EOF, when the end of the file has been reached. putc is used to write a character to a file. char ch; FILE *fp; …… putc (c, fp) ;

Example :: convert a text file to all UPPERCASE main() { FILE *in, *out ; char c ; in = fopen (“infile.dat”, “r”) ; out = fopen (“outfile.dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ; }

Contd. We can also use the file versions of scanf and printf, called fscanf and fprintf. General format: fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ; Examples: fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ; fprintf (out, “\nThe result is: %d”, xyz) ;

Command line argument Command line arguments are parameters supplied to a program, when the program is invoked. How do these parameters get into the program? Every C program has a main function. main can take two arguments conventionally called argc and argv. Information regarding command line arguments are passed to the program through argc and argv.

INTRODUCTION TO C PREPROCESSOR

C Preprocessor Overview Preprocessor Directives Conditional Compilation

Overview Six phases to execute C: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute

C Preprocessor All preprocessor directives begin with # Possible actions Inclusion of other files Definition of symbolic constants & macros Conditional compilation of program code Conditional compilation of preprocessor directives

Preprocessor Directives #define for symbolic constants #define identifier text Creates symbolic constants The “identifier” is replaced by “text” in the program Example #define PI 3.14 area = PI * radius * radius; Replaced by “area = 3.14 * radius * radius” by preprocessor before compilation

Conditional Compilation Controls the execution of preprocessor directives & compilation of code Define NULL, if it hasn’t been defined yet #if !defined(NULL) #define NULL 0 #endif Use to comment out code (for comments) #if 0 code prevented from compiling #endif

THANKS