Document Details

SteadiestWolf5558

Uploaded by SteadiestWolf5558

Department of Computer Science and Engineering

Tags

C programming computer programming programming language

Summary

This document provides an introduction to the C programming language. It covers the structure of a C program, including preprocessor directives, global and local declarations, and statements. It details concepts such as comments, identifiers, data types (both basic and derived), variables, and constants, as well as exercises and solutions.

Full Transcript

1.1 Introduction to C Language 1 Department of CSE Objectives To understand the structure of a C-Language Program To write a minimal C program To introduce the include preprocessor command To be able to create good identifiers for quantities in a program To be able to list, describe an...

1.1 Introduction to C Language 1 Department of CSE Objectives To understand the structure of a C-Language Program To write a minimal C program To introduce the include preprocessor command To be able to create good identifiers for quantities in a program To be able to list, describe and use the basic data types in C To be able to create and use variables and constants in a C program 2 Department of CSE Agenda Background of C Language Structure of a C program C Comments Identifiers in C Data types in C Variables in C Constants in C 3 Department of CSE Background of C C is a middle level language it combines the best elements of high-level languages with the control and flexibility of assembly language Like most modern languages, C is also derived from ALGOL 60 (1960) Developed by Dennis Ritchie in 1972 using many concepts from its predecessors – ALGOL,BCPL and B and by adding the concept of data types American National Standards Institute (ANSI) began the standardization of C in 1983 which was approved in 1989 In 1990 International Standards Organization (ISO) adopted the ANSI standard version known as C89 Minor changes were made to C89 in 1995 which came to be known as C95 Much more significant updates were made in 1999 and named as C99 4 Department of CSE Features of C C is a structured programming language which allows compartmentalization of code and data A structured language offers a variety of programming possibilities. For example, structured languages typically support several loop constructs, such as while, do-while, and for. A structured language allows one to place statements anywhere on a line and does not require a strict field concept In a structured language, the use of goto is either prohibited or discouraged and is not the common form of program control 5 Department of CSE Structure of a C Program Preprocessor Directives To include standard input/output library file in the program Global Declarations Describes the data which is visible to all parts of the program (optional) main function is the starting point of every C int main (parameter list) program One and only one function must be named { main in a C program Local Declarations Describes the data used in the function Visible only inside the function (optional) Statements } Follows the local declaration section Contains the instructions for the computer to do something (e.g., add two numbers) Other functions as required Optional functions also called modules similar to main to accomplish specific tasks 6 Department of CSE Dissecting a minimal C program #include Preprocessor Directive to int main(void) include stdio.h file { main function printf(“Welcome to Computer Programming”); return 0; Instruction to print a message } Instruction to stop the program The first C program has Preprocessor Commands which are placed at the beginning of the program starting with # sign can start at any column but traditionally start at column 1 tells the compiler to include standard input/output library file (stdio.h) in the program which is needed for printing the welcome message on the screen must be typed exactly as shown above without any space between # and include and the file name is written between < and >. 7 Department of CSE Dissecting the minimal C program General Syntax (writing format) of a Preprocessor Directive is #include Examples: #include - Required for using input/ output instructions #include - Required for using pre-defined string functions #include - Required for using pre-defined math functions Main function Executable part of the program begins with main function General Syntax: int main(void) The word int before the main indicates that the function will return an integer value to the operating system Since in this program main does not require any parameters, the parameter list is specified as void Creating and Compiling the minimal C program In the linux environment, locate gedit and open the editor Type in the minimal C program exactly with all puncuations as follows #include int main(void) { printf(“Welcome to Computer Programming”); return 0; } After typing the preceding source code, save the program as welcome.c. Instead of welcome, any name can be chosen, but the extension must be.c. This extension is the common convention in C programs and identifies the contents of the file as C source code. Most compilers will expect the source file to have the extension.c, and if it doesn‟t, the compiler may refuse to process it. After saving the program, locate terminal and type cc welcome.c near the $ symbol Executing the minimal C program If the program is present in the correct path and is error free, the compilation results in a $ being displayed right below the previous command typed If there is a syntax error, open the file again using gedit, locate the line number indicated by the compiler and do the necessary corrections If the compiler says file not found, change into the folder which contains the program to be compiled and repeat the compilation step Upon successful compilation, type./a.out at the $ prompt and the program must print Welcome to Computer Programming Summary of writing and executing a C program C Comments Placed by the programmer in the code to help the reader to understand the meaning of sections of code which are not very clear Comments are merely internal program documentations Compiler ignores the comments when it translates the program into executable code To identify a comment, C uses two different comment formats: Line Comment Block Comment Line Comment The Second format, the line comment uses two slashes - // to identify a comment This format does not require an end-of-comment token The end of line automatically ends the comment Programmers generally use this format for short comments The line comment can start anywhere on a line and ends with the end of that line Examples of Line Comment: //This is a whole line comment A=5; //This is a partial line comment Block Comment Block comment is used when a comment spans several lines It uses opening and closing comment tokens Each comment token is made up of two characters without spaces in between them The opening comment token is represented as Everything that is placed in between is ignored by the compiler The block comments can start in any column and they need not both be on the same line The only restriction is that the opening token Block Comment - Examples Caution with Comments Comments cannot be nested i.e., comments cannot be given inside comments Example: outer comment*/ ignored Matches the first Therefore, the opening token of the nested comment is not recognized and the closing token of the nested comment matches the outer opening comment thereby leaving the closing token of the outer comment without a matching opening token Minimal C program revisited with comments #include // this is a preprocessor directive int main(void) // this is the main function { //main begins here //No local declarations needed for this simple program //Statements printf(“Welcome to Computer Programming”); //This is a print statement return 0; //returns the control back to the operating system } //main ends here The C Character Set Character set specifies the valid symbols that can be used in a C program The C character set consists of the following symbols and escape sequence characters Escape Sequence characters Escape sequence characters are a ASCII Character Escape representation combination of two characters but null character „\0‟ treated as a single character. alert (bell) „\a‟ Often used in printf statements,they are not printed explicitly on the backspace „\b‟ screen but the effect of these horizontal tab „\t‟ characters can be observed. newline „\n‟ The table beside shows some ASCII vertical tab „\v‟ characters and their corresponding escape character format form feed „\f‟ carriage return „\r‟ single quote „\‟‟ double quote „\”‟ backslach „\\‟ Exercises Write a program that will output your name and address using a separate printf() statement for each line of output Write a program to print the pattern of asterisks as shown below Write a program to print the following figure using suitable characters Solutions to Exercises #include int main() { printf("Raghesh Krishnan K, "); printf("Asst.Professor, CSE Dept, "); printf("Amrita School of Engineering, "); printf("Amrita Vishwa Vidyapeetham, "); printf("Amrita Nagar Post, "); printf("Coimbatore 641 112 "); return 0; } Solutions to Exercises //Prints a triangular pattern - Author: Raghesh Krishnan K #include int main() { printf("*\n"); //prints first line printf("*\t*\n"); printf("*\t*\t*\n"); printf("*\t*\t*\t*\n"); //prints last line return 0; } Solutions to Exercises //Prints a pattern - Author: Raghesh Krishnan K #include int main() { printf("---------- ----------\n"); //prints the top horizontal bar printf("| | >>---> | |\n"); printf("| | | |\n"); printf("---------- ----------\n"); //prints the top horizontal bar return 0; } Identifiers in C – (Recollect Name Bindings in CTPS) Identifiers allow us to name data and other user created components in a program Each identified component is stored at a unique location in the computer‟s memory With no identifiers to symbolically represent data locations, we should know and use the component‟s memory address Using Identifiers, we simply name the data and let the computer keep track of where they are physically located in the computer‟s memory Rules for Identifiers in C The only valid alphabets to be used for naming are upper case letters from A to Z and lower case letters from a to z _ (underscore) is the only special symbol that can be used in an identifier Numeric symbols from 0 to 9 can be used but the first symbol of an identifier cannot be a numeric symbol The first symbol of an identifier must be an alphabet or an underscore Typically application programs do not use underscore as the first symbol because many of the identifiers in C system libraries start with an underscore Duplication of system names for identifiers could be confusing Last but not the least, C has 32 keywords also known as reserved words, which have a predefined meaning and cannot be used as identifier names. Some Keywords/Reserved words in C Examples of Valid and Invalid Identifier Names Valid Names Invalid Names a //valid but poor style $sum //$ not allowed student_name //ok 2names //first character should not be a digit _aSystemName //valid but similar to Sum-salary //Hyphen not allowed system identifier pattern _Bool //Boolean System id Stdnt Nmbr //Spaces not allowed INT_MIN //System Defined Value int //keyword not allowed Exercises: Identify whether the following identifiers are valid. If not give reason and correct them (a) record1 (b) #tax (c) name_and_address (d) 1record (e) name (f) name-and-address (g)file_3 (h) name and address (i) return (j) 123-45-6789 Assume a version of C that can recognize only the first 8 characters of an identifier name, though the identifier names can be arbitrarily long. Which of the following pairs of identifier names are considered to be identical and which are distinct? (a) name, names (b) address, Address (c) list1, Iist2 (d) char1,char_1 (e) identifier_1, identifier_2 (f) answer, ANSWER Solution to Exercises (a) record1 - valid (b) #tax - invalid (#character not allowed) (c) name_and_address - valid (d) 1record – invalid – first character cannot be a number (e) name – valid (f) name-and-address – invalid (hyphen not allowed) (g)file_3 - valid (h) name and address - invalid (spaces not allowed) (i) return – invalid (keyword) (j) 123-45-6789 – invalid (contains all numbers) (a) name, names - distinct (b) address, Address - distinct (c) list1, Iist2 – distinct (d) char1,char_1 - distinct (e) identifier_1, identifier_2 - identical (f) answer, ANSWER - distinct Types in C A type defines a set of values and a set of operations that can be applied on those values For example a light switch can be compared to a type It can have two values on and off Only two operations can be applied to the light switch: turn on and turn off The defined set of types in C can be divided into four general categories: void, integral, floating-point and derived Types in C C Types void Integral Floating Point Derived Boolean Character Integer Real Imaginary Complex Types in C Void type: Is designated by the key word void Has no values and no operations Very useful type Used in cases where a function has no parameters or return values and for many other purposes which will be covered in the forthcoming topics Integral type: Integral types cannot contain fractional parts i.e., they can contain only whole number quantities C Language has three kinds of integral types: Boolean, Character and Integer Types in C Boolean: Can represent only two values: true or false Is referred to by the key word bool Boolean type is stored in the memory as 0 or 1 Character: A character data type holds any single symbol from the C character set Is referred to by the key word char The size of a character is 1 byte or 8 bits Integer: Is a number without a fraction part (whole numbers) C supports four different sizes of integer data types: short int, int, long int and long long int C defines these data types so that they can be organized from smallest to largest Types in C Integer No of Minimum value Maximum Value Type Bytes that can be stored that can be stored short int 2 -32,768 32,767 int 4 -2,147,483,648 2,147,483,647 long int 4 -2,147,483,648 2,147,483,647 long long int 8 -9,223,372,036,854,775,807 9,223,372,036,854,775,806 A short int can also be referred to as short A long int can also be referred to as long A long long int can also be referred to as long long Although the size of a data type is machine dependent, c requires the following relation ship to be always true: size of short

Use Quizgecko on...
Browser
Browser