Docsity

Introduction to C programming, Study notes of C programming

Partial preview of the text

Download Introduction to C programming and more Study notes C programming in PDF only on Docsity!

INTRODUCTION TO C PROGRAMMING

C Language was design by Dennis Ritchie at Bell Laboratories in the early 1970’s. The early version of C called B was written by Ken Thompson who adopted it from Martin Richards BCPL (Basic Combined Program Language) Dennis Ritchie studied BCPL, improved and named it C which is second letter of BCPL. STRUCTURE OF C LANGUAGE C is a structured language made up of procedures, which consist of declarations, statements and other elements. Due to this structured ness, the programs are written clearly which makes them easy to maintain. In general a C program consists of 1 or more functions of which Main is a special function. C compilers will start execution from the function name Main and every C program must have this function, the other functions can be from C library or custom defined. C is also called a block-oriented language. A block is a set of statements that are connected logically. It can have its own declarations and initializations. The variables declared in a block are alive only inside the block and these variables are called local variables. After the execution of a block the memory occupied by the variables that are declared inside the block are released for future use in the program. Such a concept of allocating and releasing memory is known as Dynamic Storage Allocation. All the statements within a given function should be present within the “curly braces” and each statement should be delimited with a semicolon (;). Comments in C language are present within the pair of /* and */ The structure of a C program consist of the following parts: - a.) Pre-processor Directives b.) Variables and functions declarations c.) Main function d.) Other functions A. PRE-PROCESSOR DIRECTIVES

C compilers can be instructed to process some instructions in a C program during compilation. These instructions are called C pre-processor commands / pre-processor directives which should be present in the C program. There are 3 types of pre-processor directives available in C. Inclusion - # include Macro substitution - # define Conditional Directives - # if

  1. #include Commonly used functions like input, output and mathematical functions are stored as library functions these programs are called header files and come along with the compiler. The programmer doesn’t have to write programs to carry out such functions but instead just calls the function, using these # include pre-processor directives. During compilation process, the files mentioned with these directives are included in the current program i.e. the # include pre￾processor command is replaced by the entire program in the name which is mentioned in the # include. The syntax to include the header file is: #include or #include”filename” e.g. An Introduction to C programming #include #include #include II. MACRO DIRECTIVES By the pre-processor command #define, a symbol is assigned a value inside the program whenever the program is used it is replaced by the value during compilation process. Syntax: #define symbol Value E.g. #define Pi 3. In this case Pi is a symbolic constant whose value is 3.14287143 for example the expression

the function that marks the beginning and end of the program. C compilers starts execution from this function. An Introduction to C programming By D. OTHER FUNCTIONS All other functions call from [main( )] for any other function can be present after the statement of [main( )] though this sequence is followed always C compilers allow to have other function statements to appear before the main program function but the C compiler starts from [main().] LEXICAL ELEMENTS OF C LANGUAGE Conventionally, lexical elements are language constructors that represent element unit of meaning. The character set, constants, variables, reserved words are the fundamental raw materials with which C is built and hence are called the lexical elements of C language. C CHARACTER SET Similar to the natural languages computer languages also have a well defined character sets, grammar rules (syntax). The 2 character sets in C language are: i. Source Character – Using this the source text is created. ii. Execution Characters – are interpreted at the same time of execution. SOURCE CHARACTERS Alphabets: A to Z, a to z and _ (underscore). Decimal: 0 to 9 Special characters: %, =, !, &, ( ), [ ], {}, ;, , #, *, / EXECUTION CHARACTERS / ESCAPE SEQUENCES If you want certain characters e.g. A – Z to appear during program execution you can just type them by pressing the appropriate keys on the keyboard. However some characters such as tab, backspace cant be printed or displaced. C provides the mechanism to get such characters that are invisible or difficult to get. Each of the execution characters / escape sequences will provide a unique interpretation defined value which can be stored in a single character. Escape sequences are represented by a back slash followed by the character though there 2 characters in an escape sequence, they are considered as

a single character some of them are shown below: Execution Character Meaning Results At Execution Time \n End of a line Moves the active position to the initial position of the next line \r Carriage return Moves the active position to the initial position of the current line \v Vertical Tab Moves the active position to the next tabulation position \t Horizontal tab Moves the active position to the next horizontal tab \a Alert Produces an audible sound \b Backspace Moves the active position on the previous position of the current line \ Backslash Presents a () at the execution time CONSTANTS A constant is a symbolic name that represents a value that cannot be changed during the execution of a program. Each constant has a type, which is determined by its form and value. There are 3 types of constants in C: - i. Numeric Constants ii. Character Constants iii. String Constants NUMERIC CONSTANTS Is made up a sequence of numeric digits with optional presence of a decimal point (.) The 2 types of numeric constants are: - a. Integer Numeric Constants – A sequence of numeric digits without a point (whole numbers). b. Floating point numeric constants – A sequence of numeric digits with a decimal point (fraction numbers) C allows the calculation and arithmetic expressions with decimals, octal and hexadecimal

They are: - Hash (#) pre-processor directive Comma (,) variable delimiter in variable list Semicolon (;) statement delimiter Colon (:) label delimiter Parenthesis ( ) used in expression Square blanket [ ] used in arrays Cary braces {} used in block C sentences VARIABLE / IDENTIFIERS A variable is a symbolic name that is assigned a value that can change during program execution. Values can be stored in a symbolic name (variable) in the computer memory and can be recalled later when required. The number or other type of data held in a variable is called its value. Every variable in C must be declared. When you declare a variable, you are telling the compiler and ultimately the computer what kind of data you’ll be storing in the variable. The kind of data that is held in a variable is called its type and the name for the type such as int or float is called type name. Ideally the variables should be given a name that describes / transmits an idea of what value they hold. E.g. if you are writing a program to calculate the circumference of a circle you can name the variable that will hold the value of the radius as rad or radius and the one that will hold the value of the circumference as Circ or Circumference rather than use letters e.g. a, b, x, z which don’t reflect which values they hold. NAMING OF VARIABLES In any given program the variable name should be unique. I.e. no 2 variables should have the same name. Some rules should be followed when naming variables.

  1. Can be made up of letters, digits and underscore.
  2. No other special characters are allowed
  1. First character should be letter, underscore. Letters, digits or underscore, can then follow.
  2. Upper and lower case letters are significant, both cases are allowed E.g. RADIUS, radius, rADIUS are considered to be 3 different variables
  3. Reserved words cannot be used as identifier names. Examples: Valid Invalid Remark Radius 7th First character is a digit a void void is a reserved word net_pay time?? is a special character _root No DATA TYPES AND SIZES There are 4 types of variables supported by C language: - TYPE SIZE REMARKS char 1 byte Can hold a single character int 2 bytes can hold an integer value float 4 bytes single precision floating point value double 8 bytes Double precision floating point values One of the reserved words start in ‘short’ or ‘long’ can be specified together with int. the words signed in single quotes or unsigned can also be specified with int these words are called qualifiers. E.g. Short int, long int, unsigned int, signed int. VARIABLE DECLARATION Through the declaration statements C interprets the identifier in a specific format. A declaration causes storage to be reserved for an identifier. All C variables should be declared before they are used usually at the beginning of the function before any executable statement. When declaring any variable you declare its type variable and initialization. The syntax for that is: Type variable list

printf(“\n”); } EXPRESSIONS A C expression is a combination of operators, constants, variables and function calls that result in a single value. An expression is always a part of the statement expressions are generally classified as arithmetic, relational and logical expressions. STATEMENTS They are language constructors that represent a set of declarations or steps in a sequence of actions. C language program can be written in statements following some rules. These set of rules are called syntax. The statements are executed in sequence and they are delimited by a semicolon. NULL STATEMENT A null statement in C is presented by a single semicolon which is the statement delimiter e.g. ; Null statement EXPRESSION STATEMENT An arithmetic expression is a constant, variable or combination of constants and variables. It can also include a function call. Example: x1=(-b + d) / (2 * a); – Expression statement big (a,b,c); - Function call BLOCK OF STATEMENTS In a C language, some statements can be grouped together to make a block by giving them within cury braces ({ }) such blocking is made for specific purposes such as execution repetition of a group of statements. A block may have its own set of declarations and initializations. Example: { d=b * b – 4 * a * c; /*Block of statements / d1=sqrt(d); / given with { and } */

x1=(-b * d1) / (2 * a); x2=(-b - d) / (2 * a); } LABELLED STATEMENTS Any statements may be preceded by a prefix that declares an identifier as a label name. Label in themselves don’t alter the flow of control but given the provision so that through other statements transfer of control flow of the labelled statements is possible. CONDITIONAL CONTROL STATEMENTS The statements through which the flow is controlled are known as control statements e.g. if, if … else, if …. LOOP CONTROL STATEMENTS The repeated execution of the same block of statements is possible with loop statements e.g. do … while, while and for INPUT / OUTPUT IN C Input and output statements of computer language are used to provide communication between the user and the program. In most of the computer languages input and output are done through statements but in C these operations are carried out through built in functions. Through these functions data can be read from or within to files or standard input / output devices like the keyboard and VDU. The execution of a program can be interpreted by Input / Output calls. CONVERSION SPECIFICATIONS They are used to provide the type and size of data. The list below shows the characters that are used for conversion specification. A percent symbol (%) should precede the conversion character in input / output function calls. d – Decimal integers f – floating point numbers o – an octal integer x – a hexadecimal integer c – a single character

Examples: i. scanf (“%d”,&basic_pay); In this example the scanf function is called with 2 parameters. In the first parameter %d symbol implies that one integer value should be read. The second parameter is &basic_pay and this is a variable name in which the accepted integer vale will be stored. ii. scanf (“%c %c”,&oscar,&kamau); The first parameter (control string) determines that there are 2 characters following as successor parameter. Two characters are read and stored in the variables Oscar and kamau. iii. scanf (“%d %f %c”,&basic_pay,&height,&gender); In the control string (1st parameter) there are 3 conversion specifications. At the time of execution of the statement the system waits for 3 values (one integer, one float and one character type data) they are accepted and stored in 3 different variables namely basic_pay, height and gender. For the above e.g. the data can be entered with space as the delimiter e.g. 6500 1.7 M N.B. When scanf is used the input value can be delimited as space (default). A specific character may be placed between 2 conversion specifications to act as a delimiter. The following 2 examples illustrate this feature.

  1. scanf (“%d %f”,&basic_pay,&height); Input data may be 6500 1.
  2. scanf (“%d %f”,&basic_pay,&height); input data may be 2200 1000. OUTPUT FUNCTIONS Throughout functions, the results or information can be got from the computer the user can get data or results on the standard output device such as monitor, or data can be written to another file in a secondary device such as a disk or tape. C language supports many output functions. 2 of them are discussed below. putch This function is used to output only character type data. The value of a character type variable is displayed.

Syntax: putch (var) Each time the putch () function is called, it returns one output character i.e. represented by the argument variable. Example: C = getch(); K = putch(); printf This function is used to output all types of values. It works in the same manner as scanf function but the fist parameter can also contain string constants. The remaining parameters can also be constant, variables or expressions. Example1: (num1.c) #include - includes some of the input and output functions #include - includes mathematical functions Example: write a program that records 3 integers and prints the sum and average of the numbers. #include #include void main ( ) { int a,b,c; printf(“Enter 3 numbers: “); scanf(“%d %d %d”,&a,&b,&c); printf(“\nsum=%d,\nAverage =%f”,a+b+c,(a+b+c)/3); } Example 2: (num2.c) Write a program that reads 2 numbers i,j and finds i+j, I-j, i*j and i/j #include #include void main () {

area = 22.0/7 * radius * radius; circ = 22.0/7 * radius * 2; printf(“\nArea = %f\nCircumference = %f”,area,circ); } FORMATTED INPUT / OUTPUT Input and output statements can have format specifications through which better presentation results can be obtained. FORMAT FOR INTEGER INPUT wd – w is the width / number of digits Let the input statement be: scanf(“%2d %4d”,&i, &j); i. When input data length is lesser than the given length the given values are unaltered. E.g. Let the input for the above be 17 32. Results: 17 is stored in i and 32 is stored in j. ii. When the input is equal to the given length the given values are unaltered e.g. let the input for the above scanf be 17 1728. Result: 17 is stored in i and 1728 is stored in j iii. When input data length is more than the given length the given values are altered as shown in the following example. Let the input for the above scanf be 276 and 34712. Result: 27 is stored in i and 6 is stored in j FORMAT FOR INTEGER OUTPUT wd – W is the width or number of digits Let the output statement be: Printf(“Sum = %2d and std deviation = %4d”,i,j); When output data length is lesser than the given length, equal to the given or more than the given length, the values are displayed without alteration. Let i = 17 and j = 32 The result will be sum = 17 and std deviation = 32 (with 2 leading blanks for the second data) Example 2:

Let i = 17 and j = 3246. The result will be sum = 17 and std deviation = 3246 Example 3: Let i = 157 and j = 23465. The result will be sum = 157 and std deviation = 2365 FORMAT FOR FLOATING POINT NUMERIC INPUT wf- w represents the total width which includes the digits before, after decimal place and the decimal point. Let the input statement be: Scanf(“%4f %6f”&p,&q); i. When input data length is less than the given length the given values are unaltered e.g. Let input for the above scanf be 17 26. Result: 17 is stored in p and 26.1 is stored in q ii. When the input data length is equal to the given length the given values are unaltered. Let the input for the above scanf be 17.6 261. Result: 17.6 is stored in p and 261.72 is stored in q iii. When the input data length is more than the given length the given values are altered as shown in the following example. Let the input for the above scanf be 62.457 2768. Result: 62.4 is stored in p and 57 is stored in q FORMAT FOR FLOATING POINT NUMERIC OUTPUT w.df – d is the number of digits after decimal point, w represents the total width which includes the digits before, after the decimal place and decimal point. Let the output statement be printf(“sum = %4.1f and average %6.2f”,p,q); When output data length is less than the given length, equal to the given length or more than the given length the values are displayed without alteration before the decimal point and truncation (or rounding off) takes place after the decimal point. Example: Let p = 16.8 and q = 32. Result: sum = 16.8 and average = 32. Example 2: Let p = 16.8 and average = 32.

OPERATORS & EXPRESSIONS

An operator specifies an operation to be performed that yields a value. It provides a side effect after the operation is performed. An operand is an entity on which an operation acts. C language operators are classified into 4 types as arithmetic, relational, logical and assignment operators. These operators can be categorized as follows: Unary operators: Requires one operand. Binary Operator: requires two operands Ternary operators: requires three operands ARITHMETIC OPERATORS AND EXPRESSIONS Arithmetic operators are used in calculations. An arithmetic expression is made up of constants, variables a combination of both or a function call connected by arithmetic operators. UNARY ARITHMETIC Requires only one operand. Unary - and unary + E.g. – a +k BINARY ARITHMETIC Requires 2 operands.

  • plus
  • Minus
  • asterisk in multiplication / slash for division % modulus operation in remainders. N.B. % cannot be applied with floats or double. Example Deduction + 6.0 / 100 * pay a + b * b / 2 TERNARY ARITHMETIC This is one of the special features. It requires 3 operands.

Syntax: test operand? Operand1, operand if the test operand results true then the value of operand1 is taken otherwise the value of operand is taken for further processing. Example big = a>b? a:b; In the above assignment if a > b then a is assigned to big otherwise b is assigned to big. HIERARCHY OF OPERATORS Though the expressions are presented by a sequence of operators and variables, the c compliers follows a hierarchy to execute them in order. The hierarchy of an arithmetic expression is given here below.

    • / % - Evaluated from left to right
      • Evaluated from left to right The sub expressions within the parenthesis are evaluated first following the above hierarchy. The sub expressions present in the innermost parenthesis are evaluated first. Examples:
  1. a + b – c /*a and b are added first and then c is subtracted from the result */
  2. i + j / k /* j is divided by k and the net result is added with I */
  3. (i + j ) / k * n % m – 5 * b
  4. a + b * c / d % e – ((8 * c) + 15 / (b * d) ) When writing out expressions as parenthesis should exist at the appropriate places. The following examples illustrate this. Algebraic expression C expression a.) k + 14 k + 14 b.) a c a / b * c b c.) a a / (b * c) bc d.) b
  • 4 ac b * b – 4 * a * c