Basics of C programming, Summaries of C programming

this is a very basics of c programming with some basic programs in it .

Typology: Summaries

2023/2024

Uploaded on 01/14/2026

john-b7g
john-b7g 🇮🇳

1 document

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C PROGRAMMING BASICS
Problem formulation Problem Solving - Introduction to ‘ C’ programming –fundamentals structure of a ‘C’
program compilation and linking processes Constants, Variables Data Types Expressions using operators
in ‘C’ – Managing Input and Output operations Decision Making and Branching Looping statements
solving simple scientific and statistical problems.
INTRODUCTION TO C
As a programming language, C is rather like Pascal or Fortran.. Values are stored in variables. Programs are
structured by defining and calling functions. Program flow is controlled using loops, if statements and function
calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or
structures.
Of the three languages, C allows the most precise control of input and output. C is also rather more terse than
Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's
range of powerful operators. It also allows the programmer to produce programs which are impossible to
understand. Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct
term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead
to errors which are very hard to trace. This course only deals with the simplest applications of pointers.
A Simple Program
The following program is written in the C programming language.
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
}
BASIC STRUCTURE OF C PROGRAMS
C programs are essentially constructed in the following manner, as a number of well defined sections.
/* HEADER SECTION */
/* Contains name, author, revision number*/
/* INCLUDE SECTION */
/* contains #include statements */
/* CONSTANTS AND TYPES SECTION */
/* contains types and #defines
*/
/* GLOBAL VARIABLES SECTION */
/* any global variables declared here
*/
/* FUNCTIONS SECTION */
/* user defined functions
*/
/* main() SECTION */
intmain() {
}
CONSTANTS
A constant is an entity that doesn’t change whereas a variable is an entity that may change.
Types of C Constants
C constants can be divided into two major categories:
(a) Primary Constants
(b) Secondary Constants
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Basics of C programming and more Summaries C programming in PDF only on Docsity!

C PROGRAMMING BASICS

Problem formulation – Problem Solving - Introduction to ‘ C’ programming –fundamentals – structure of a ‘C’ program – compilation and linking processes – Constants, Variables – Data Types – Expressions using operators in ‘C’ – Managing Input and Output operations – Decision Making and Branching – Looping statements – solving simple scientific and statistical problems.

INTRODUCTION TO C

As a programming language, C is rather like Pascal or Fortran.. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures. Of the three languages, C allows the most precise control of input and output. C is also rather more terse than Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand. Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead to errors which are very hard to trace. This course only deals with the simplest applications of pointers. A Simple Program The following program is written in the C programming language. #include <stdio.h> main() { printf("Programming in C is easy.\n"); }

BASIC STRUCTURE OF C PROGRAMS C programs are essentially constructed in the following manner, as a number of well defined sections. /* HEADER SECTION / / Contains name, author, revision number/ / INCLUDE SECTION / / contains #include statements / / CONSTANTS AND TYPES SECTION / / contains types and #defines / / GLOBAL VARIABLES SECTION / / any global variables declared here / / FUNCTIONS SECTION / / user defined functions / / main() SECTION */ intmain() { }

CONSTANTS

A constant is an entity that doesn’t change whereas a variable is an entity that may change.

Types of C Constants

C constants can be divided into two major categories: (a) Primary Constants (b) Secondary Constants

Rules for Constructing Integer Constants (a) An integer constant must have at least one digit. (b) It must not have a decimal point. (c) It can be either positive or negative. (d) If no sign precedes an integer constant it is assumed to be positive. (e) No commas or blanks are allowed within an integer constant. (f) The allowable range for integer constants is -32768 to 32767.

Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler like Turbo C or Turbo C++ the range is – 32768 to 32767. For a 32-bit compiler the range would be even greater. Question like what exactly do you mean by a 16-bit or a 32-bit compiler, what range of an Integer constant has to do with the type of compiler and such questions are discussed in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit compiler. Ex.: 426

Rules for Constructing Real Constants Real constants are often called Floating Point constants. The real constants could be written in two forms— Fractional form and Exponential form. Following rules must be observed while constructing real constants expressed in fractional form: (a)A real constant must have at least one digit. (b)It must have a decimal point. (c)It could be either positive or negative. (d)Default sign is positive. (e)No commas or blanks are allowed within a real constant.

Ex.: +325.

-32. -48. The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesn’t restrict us in any way from using exponential form of representation for other real constants. Rules for Constructing Character Constants A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, ’A’ is a valid character constant whereas ‘A’ is not. The maximum length of a character constant can be 1 character.

Ex.: 'A' 'I' '5' '=' VARIABLES User defined variables must be declared before they can be used in a program. Variables must begin with a character or underscore, and may be followed by any combination of characters, underscores, or the digits 0 - 9. LOCAL AND GLOBAL VARIABLES Local

auto int avar = 0; static int svar = 0; printf("auto = %d, static = %d\n", avar, svar); ++avar; ++svar; } main() { int i; while( i < 3 ) { demo(); i++; } } Automatic and Static Variables Example: /* example program illustrates difference between static and automatic variables / #include <stdio.h> void demo( void ); / ANSI function prototypes */ void demo( void ) { auto int avar = 0; static int svar = 0; printf("auto = %d, static = %d\n", avar, svar); ++avar; ++svar; } main() { int i; while( i < 3 ) { demo(); i++; } } Program output auto = 0, static = 0 auto = 0, static = 1 auto = 0, static = 2 The basic format for declaring variables is data_type var, var, ... ; where data_type is one of the four basic types, an integer, character, float, or double type. Static variables are created and initialized once, on the first call to the function. Subsequent calls to the function do not recreate or re-initialize the static variable. When the function terminates, the variable still exists on the _DATA segment, but cannot be accessed by outside functions. Automatic variables are the opposite. They are created and re-initialized on each entry to the function. They disappear (are de-allocated) when the function terminates. They are created on the _STACK segment. DATA TYPES The four basic data types are INTEGER These are whole numbers, both positive and negative. Unsigned integers (positive values only) are supported. In addition, there are short and long integers. The keyword used to define integers is, int An example of an integer value is 32. An example of declaring an integer variable called sum is, int sum; sum = 20;

FLOATING POINT These are numbers which contain fractional parts, both positive and negative. The keyword used to define float variables is,

float An example of a float value is 34.12. An example of declaring a float variable called money is, float money; money = 0.12; DOUBLE These are exponetional numbers, both positive and negative. The keyword used to define double variables is, double An example of a double value is 3.0E2. An example of declaring a double variable called big is, double big; big = 312E+7; CHARACTER These are single characters. The keyword used to define character variables is, char An example of a character value is the letter A. An example of declaring a character variable called letter is, Char letter; letter = 'A'; Sample program illustrating each data type Example: #include < stdio.h > main() { int sum; float money; char letter; double pi; sum = 10; /* assign integer value / money = 2.21; / assign float value / letter = 'A'; / assign character value / pi = 2.01E6; / assign a double value */ printf("value of sum = %d\n", sum ); printf("value of money = %f\n", money ); printf("value of letter = %c\n", letter ); printf("value of pi = %e\n", pi ); } Sample program output value of sum = 10 value of money = 2. value of letter = A value of pi = 2.010000e+ INITIALISING DATA VARIABLES AT DECLARATION TIME In C variables may be initialised with a value when they are declared. Consider the following declaration, which declares an integer variable count which is initialised to 10. int count = 10; SIMPLE ASSIGNMENT OF VALUES TO VARIABLES The = operator is used to assign values to data variables. Consider the following statement, which assigns the value 32 an integer variable count, and the letter A to the character variable letter count = 32; letter = 'A' Variable Formatters %d decimal integer %c character %s string or character array

If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement loop = ++count; really means increment count first, then assign the new value of count to loop. THE RELATIONAL OPERATORS These allow the comparison of two or more variables. == equal to != not equal < less than <= less than or equal to

greater than = greater than or equal to Example: #include <stdio.h> main() /* Program introduces the for statement, counts to ten */ { int count; for( count = 1; count <= 10; count = count + 1 ) printf("%d ", count ); printf("\n"); } RELATIONALS (AND, NOT, OR, EOR) Combining more than one condition These allow the testing of more than one condition as part of selection statements. The symbols are LOGICAL AND && Logical and requires all conditions to evaluate as TRUE (non-zero). LOGICAL OR || Logical or will be executed if any ONE of the conditions is TRUE (non-zero). LOGICAL NOT! logical not negates (changes from TRUE to FALSE, vsvs) a condition. LOGICAL EOR ^ Logical eor will be excuted if either condition is TRUE, but NOT if they are all true. Example: The following program uses an if statement with logical AND to validate the users input to be in the range 1-10. #include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d", &number); if( (number < 1 ) || (number > 10) ) { printf("Number is outside range 1-10. Please re-enter\n"); valid = 0; } else valid = 1; } printf("The number is %d\n", number ); } Example: NEGATION

#include <stdio.h> main() { int flag = 0; if(! flag ) { printf("The flag is not set.\n"); flag =! flag; } printf("The value of flag is %d\n", flag); } Example: Consider where a value is to be inputted from the user, and checked for validity to be within a certain range, lets say between the integer values 1 and 100. #include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 100"); scanf("%d", &number ); if( (number < 1) || (number > 100) ) printf("Number is outside legal range\n"); else valid = 1; } printf("Number is %d\n", number ); } THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR This conditional expression operator takes THREE operators. The two symbols used to denote this operator are the? and the :. The first operand is placed before the ?, the second operand between the? and the :, and the third after the :. The general format is, condition? expression1 : expression If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its result becomes the result of the operation. An example will help, s = ( x < 0 )? -1 : x * x; If x is less than zero then s = - If x is greater than zero then s = x * x Example: #include <stdio.h> main() { int input; printf("I will tell you if the number is positive, negative or zero!"\n"); printf("please enter your number now--->"); scanf("%d", &input ); (input < 0)? printf("negative\n") : ((input > 0)? printf("positive\n") : printf("zero\n")); } BIT OPERATIONS C has the advantage of direct bit manipulation and the operations available are, Operation Operator Comment Value of Sum before Value of sum after

\n newline \t tab \r carriage return \f form feed \v vertical tab Scanf (): Scanf () is a function in C which allows the programmer to accept input from a keyboard. Example: #include <stdio.h> main() /* program which introduces keyboard input */ { int number; printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); } FORMATTERS FOR scanf() The following characters, after the % character, in a scanf argument, have the following effect. d read a decimal integer o read an octal value x read a hexadecimal value h read a short integer l read a long integer f read a float value e read a double value c read a single character s read a sequence of characters [...] Read a character string. The characters inside the brackets Accepting Single Characters From The Keyboard Getchar, Putchar getchar() gets a single character from the keyboard, and putchar() writes a single character from the keyboard. Example: The following program illustrates this, #include <stdio.h> main() { int i; int ch; for( i = 1; i<= 5; ++i ) { ch = getchar(); putchar(ch); } } The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch) to the console screen. DECISION MAKING IF STATEMENTS The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions. The basic format is, if( expression ) program statement; Example:

if( students < 65 ) ++student_count; In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65. The following program uses an if statement to validate the users input to be in the range 1-10. Example: #include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d", &number); /* assume number is valid */ valid = 1; if( number < 1 ) { printf("Number is below 1. Please re-enter\n"); valid = 0; } if( number > 10 ) { printf("Number is above 10. Please re-enter\n"); valid = 0; } } printf("The number is %d\n", number ); } IF ELSE The general format for these are, if( condition 1 ) statement1; elseif(condition2) statement2; elseif(condition3) statement3; else statement4; The else clause allows action to be taken where the condition evaluates as false (zero). The following program uses an if else statement to validate the users input to be in the range 1-10. Example: #include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d", &number); if( number < 1 ) { printf("Number is below 1. Please re-enter\n"); valid = 0; } else if( number > 10 )

count = count + 1 ); which adds one to the current value of count. Control now passes back to the conditional test, count <= 10; which evaluates as true, so the program statement printf("%d ", count ); is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of 11. When this occurs, the conditional test count <= 10; evaluates as FALSE, and the for loop terminates, and program control passes to the statement printf("\n"); which prints a newline, and then the program terminates, as there are no more statements left to execute. THE WHILE STATEMENT The while provides a mechanism for repeating C statements whilst a condition is true. Its format is, while( condition ) program statement; Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish. Example: /* Sample program including while / #include <stdio.h> main() { int loop = 0; while( loop <= 10 ) { printf("%d\n", loop); ++loop; } } The above program uses a while loop to repeat the statements printf("%d\n", loop); ++loop; whilst the value of the variable loop is less than or equal to 10. Note how the variable upon which the while is dependant is initialised prior to the while statement (in this case the previous line), and also that the value of the variable is altered within the loop, so that eventually the conditional test will succeed and the while loop will terminate. This program is functionally equivalent to the earlier for program which counted to ten. THE DO WHILE STATEMENT The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-Zero). The loop is executed as least once. Example: / Demonstration of DO...WHILE*/ #include <stdio.h> main() { int value, r_digit; printf("Enter the number to be reversed.\n"); scanf("%d", &value); do { r_digit = value % 10; printf("%d",r_digit);value=value/10; } while (value!=0); printf("\n"); }

The above program reverses a number that is entered by the user. It does this by using the modulus % operator to extract the right most digit into the variable r_digit. The original number is then divided by 10, and the operation repeated whilst the number is not equal to 0. SWITCH CASE: The switch case statement is a better way of writing a program when a series of if elses occurs. The general format for this is, switch(expression) { case value1: Program statement; program statement; break; case valuen: program statement; break; default: break; } The keyword break must be included at the end of each case statement. The default clause is optional, and isexecuted if the cases are not met. The right brace at the end signifies the end of the case selections. Example: #include <stdio.h> main() { int menu, numb1, numb2, total; printf("enter in two numbers -->"); scanf("%d %d", &numb1, &numb2 ); printf("enter in choice\n"); printf("1=addition\n"); printf("2=subtraction\n"); scanf("%d",&menu); switch( menu ) { case 1: total = numb1 + numb2; break; case 2: total = numb1 - numb2; break; default:printf("Invalidoptionselected\n"); } if( menu == 1 ) printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 ) printf("%d minus %d is %d\n", numb1, numb2, total ); } The above program uses a switch statement to validate and select upon the users input choice, simulating a simple menu of choices.