C Programming Fundamentals PDF
Document Details
Uploaded by CommendableFable
Tunis Business School
Tags
Summary
This document is a lecture for a course on C programming. The document explains C program structure, data types, variables, and arithmetic, logical, and relational operators. Examples and exercises are included to aid learners in understanding these important concepts.
Full Transcript
Chapter 2: Fundamentals of C Language 1 Chapter outcomes By the end of this chapter, the students will get familiar with a C program structure know about the fundamentals required to write a C program: primitive types, syntax rules, etc. be able to translat...
Chapter 2: Fundamentals of C Language 1 Chapter outcomes By the end of this chapter, the students will get familiar with a C program structure know about the fundamentals required to write a C program: primitive types, syntax rules, etc. be able to translate simple algorithms into a C programs 2 Structure of a C program Library Function main Algorithm ADD Variables declaration Head Var a,b,c: integer BEGIN 1− read(a , b ) Body/Statements 2−c←a+b … Body 3 − write(c) END 3 Program analysis #include: includes a set of functions from the header file (stdio.h) specified between (). main() is a special function which indicates the beginning of the program. Every C program must contain the main() function. The execution starts from this function. The left brace { indicates the beginning of the body of the main function. A corresponding right brace } must end the body of the function. Each statement in C needs to be terminated with semicolon (;) 4 C Program Structure A C program basically consists of the following parts : Preprocessor Commands : tells a C compiler to include stdio.h file (and others) before going to compilation. Functions : The main() function is where the program execution begins. Declaration : The part of the program that tells the compiler the names of memory cells in a program. Executable statements : Program lines that are converted to machine language instructions and executed by the 5 computer. C Libraries stdio.h is the library which contains the standard input/output functions. math.h defines various mathematical functions. stdlib.h defines numeric conversion functions, memory allocation and process control functions. string.h is the library which contains various functions for manipulating arrays of characters. 6 time.h defines date and time handling functions. Variables Variable : is a name associated with a memory cell whose value can change. Variable Declaration : specifies the type of a variable Example: int nb; Variable Definition: assigning a value to the declared variable Example: nb = 6; 7 Variables All variables must be declared before the use of the program. Variable names must be valid identifiers. A valid identifier can contain letters, digits and underscore “_“characters. Also, it must not begin with a digit. A declaration may contain a list of one or more variables: int x, y, z, sum; 8 Rules for naming variables 9 Basic Data Types There are 4 basic data types : Int, float, double, char int used to declare numeric program variables of integer type whole numbers, positive and negative keyword: int int number; number = 12; float fractional parts, positive and negative keyword: float float height; 10 height = 1.72; Basic Data Types double used to declare floating point variable of higher precision or higher range of numbers exponential numbers, positive and negative keyword: double double valuebig; valuebig = 12E-3; char Example of characters: Numeric digits: 0 – 9, Lowercase/uppercase letters Space (blank), Special characters: ,. ; ? “ / ( ) [ ] { } * & % ^ < > etc single character keyword: char char my_letter; The declared character must be my_letter = 'U'; enclosed within a single quote! 11 Constants Entities that appear in the program code as fixed values. Any attempt to modify a CONSTANT will result in error. Examples: Integer constants const int MAX_NUM = 10; Floating-point constants (float or double) const double VAL = 0.5877e2; (stands for 0.5877 x 102) Character constants const char letter = ‘n’ 12 Arithmetic operations in C This table contains useful arithmetic operations in C and examples: Operation C operator Example Addition + X+Y Subtraction - Z-1 Multiplication * X*Y*3 Division / X/2 Modulus % Z%X (remainder of the integer division) 13 Relational and Logical operators This table contains relational and logical operators in C: Relational Operators C operator Action > Greater than >= Greater than or equal < Less than = Left to right equality == != Left to right logical AND && Left to right Logical logical OR || Left to right Conditional ternary ?: Right to left 18 Assignment assignment = += -= *= /= %= Right to left Operators precedence and associativity in C Example 1:Try the following example to understand operator precedence in C, #include main() { The output is: printf("%d\n",12+2*3); printf("%d\n",11*3%2+12/5); 18 printf("%d\n",11>2 || 103); 3 } Note: 1 is used for True and 0 for False 1 Example 2: Solve 12 + 3 – 4 / 2 < 3 + 1 19 The standard Input/Output functions A few functions that are pre-defined in the header file stdio.h such as : printf() scanf() getchar() & putchar() 20 Output Function: printf printf : is a subprogram allowing to show its message on the screen. Example: printf(“Type a number : ”); printf(“The result is %d\n”, sum); \n is an escape sequence , moves the cursor to the new line %d is a placeholder (conversion specifier), marks the display position for a type integer variable. 21 Input function: scanf scanf : allows reading data from the keyboard. Example : scanf (“%d”, &x) The conversion specifier %d indicates the type of the input data: % is an escape character and d stands for decimal integer Note: %f corresponds to double. %c corresponds to a character. Ampersand & is the address operator. &x gives the location in memory (address of the variable x) where the value should be stored. 22 Input function: scanf If you want the user to enter more than one value, you serialize the inputs. Example: float height, weight; printf(“Please enter your height and weight:”); scanf(“%f%f”, &height, &weight); Common Conversion Identifier used in printf and scanf functions. printf scanf int %d %d float %f %f double %f or %lf %lf char %c %c 23 string %s %s getchar() and putchar() getchar() : read a character from standard input putchar() : write a character to standard output Example: #include void main() { char my_char; printf(“Please type a character: ”); my_char = getchar (); \* equivalent to: scanf(“%c”,&my_char);*\ printf(“\nYou have typed this character: ”); \* equivalent to: printf(“\nYou have typed this character: %c ”, my_char); *\ putchar(my_char); 24 } Few notes on C program C is case-sensitive Word, word, WorD, WORD, WOrD, worD, etc are all different variables / expressions Comments are inserted into the code using to end a comment; or using two slashes (//) for single line comments // This is a comment Reserved Words should be written in lowercase. Example: const, double, int, main, void, printf, while, for, 25 else Exercises Exercise 1: Write a program that asks the user to enter the radius of a circle, computes the area and the circumference define variables and initialize them use scanf to input radius variable compute the values formatted input on screen Exercise 2: Write a program that asks for two integer numbers a and b, computes the quotient and the remainder, and prints them on screen. 26