Programming in C

Introduction:

C was introduced by Dennis Ritchie at the Bell Telephone Laboratories in the year1972. As C is such a flexible and powerful language, its use rapidly spread beyond Bell Labs. Programmers everywhere start utilizing it to write all sorts of programs. Shortly though, various organizations start utilizing their own versions of C, and slight differences between implementations began to cause programmers headaches. In response to this trouble, the American National Standards Institute (ANSI) made a committee in the year1983 to establish a standard definition of C, which became termed as ANSI Standard C. With little exceptions, every modern C compiler has the capability to adhere this standard.

A Simple C Program:

A C program comprises of one or more functions that are similar to the functions and subroutines of a FORTRAN program or the procedures of PL /I and perhaps few external data definitions. ‘main’ is such a function, and however all C programs should have a main.  Execution of the program starts at the first statement of main. ‘main’ will generally invoke other functions to execute its job, some coming from similar program, and others from libraries.

main( ) { printf("hello, world"); }

printf is a library function that will format and print output on the terminal (that is, unless some other destination is specified). In this condition it prints hello, world.

A Working C Program; Variables; Types and Type Declarations:

The program which adds three integers and prints their sum.

main( ) {
               int a, b, c, sum;
               a = 1; b = 2; c = 3;
               sum = a + b + c;
               printf ("sum is %d", sum);
       }

Arithmetic and assignment statements are much similar as in FORTRAN (apart from the semicolons) or PL/I. The format of C programs is pretty free. We can put some statements on a line if we wish for, or we can split a statement among some lines if it seems desirable. The split might be between any of the operators or variables, however not in the middle of a name or operator. As a matter of style, tabs, spaces and newlines must be employed freely to enhance the readability. 

C has basic types of variables:

183_c1.jpg

There are as well arrays and structures of such basic types, pointers to them and functions that return them, all of which we will meet soon.

All variables in a C program should be declared, though this can sometimes be completely implicitly by context. Declarations should precede the executable statements. The declaration

int a, b, c, sum;

Variable names contain one to eight characters, selected from A-Z, a-z, 0-9, and _, and begin with a non-digit. 

Constants:

As C is frequently employed for system programming and bit-manipulation, octal numbers are a significant part of the language. In C, any number which starts with 0 (zero) is an octal integer (and therefore can't contain any 8's or 9's in it). Therefore 0777 is an octal constant, with decimal value 511.

A ‘character’ is one byte (that is, an inherently machine-dependent concept). Most frequently this is stated as a character constant that is one character enclosed in single quotes.

Though, it might be any quantity which fits in a byte, as in flags below:

char quest, newline, flags;
quest = '?';
newline = '\n';
flags = 077;

The sequence `\n' is a C notation for newline character, that, when printed, skips the terminal to the starting of the next line. Notice that `\n' symbolizes only a single character. There are many other ‘escapes’ such as `\n' for symbolizing hard-to-get or invisible characters, like `\t' for tab, `\b' for backspace,`\\' for backslash itself and `\0' for the end of file.

Simple I/O – getchar(), putchar(), printf ():

getchar and putchar are the fundamental I/O library functions in C. getchar fetch one character from the standard input (generally the terminal) each time it is called, and returns that character as the value of function. Whenever it reaches the end of what the file it is reading, afterward it returns the character symbolized by `\0' (ASCII NUL that has value zero).

main( ) {
               char c;
               c = getchar( );
               putchar(c);
       }

putchar places one character out on the standard output (generally the terminal) each time it is called. Therefore the program above reads one character and writes it back-out. By itself, this is not very interesting, however observes that when we put a loop around this, and add a test for end of file, we contain a complete program for copying one file to the other.

printf is a more complex function for generating formatted output.

printf ("hello, world\n");

is of simplest use. The string ``hello, world\n'' is printed out.

More complex, when sum is 6, 
       printf ("sum is %d\n", sum);
prints 
       sum is 6

In the first argument of printf, the characters `%d' means that the next argument in the argument list is to be printed as the base 10 number.

The other useful formatting commands are ``%c'' to print out a single character, ``%s'' to print out a whole string, and ``%o'' to print a number as octal rather than decimal (that is, no leading zero).  For illustration, 
        n = 511;
       printf ("What is the value of %d in octal?", n);
       printf ("%s! %d decimal is %o octal\n", "Right", n, n);

 
prints
       Determine the value of 511 in octal?  Right! 511 decimal
       is 777 octal


If - relational operators and compound statements:

The fundamental conditional-testing statement in C is the ‘if statement’:

c = getchar( );
if( c == '?' )
printf("why did you type a question mark?\n");


The simplest form of ‘if’ is
if (expression) statement

The condition to be tested is any expression enclosed in the parentheses. It is followed by a statement. The expression is computed, and if its value is non-zero, the statement is executed. There is an optional else clause.
The character sequence `==' is one of the relational operators in C; here is a complete set:

== Equal to
!= not equal to
> greater than
< Less than
>= greater than or equal to
<= less than or equal to

The value of ‘expression relation expression’ is 1 whenever the relation is true, and 0 when false. Do not forget that the equality test is `=='; a single `=' causes the assignment, not a test, and invariably leads to the disaster. 
Tests can be joint with the operators `||' (OR), `&&' (AND), and `!' (NOT). For illustration, we can test whether a character is tab or blank or newline with

if( c==' ' || c=='\t' || c=='\n' ) ...

C guarantees that `||' and `&&' are computed left to right -- we shall soon see situations where this matters. 
As a simple illustration, assume that we want to make sure that a is bigger than b, as part of a sort routine. The interchange of a and b takes three statements in C, grouped altogether by {}:

if (a < b) {
               t = a;
               a = b;
               b = t;
       }

As a common rule in C, anywhere you can employ a simple statement, you can utilize any compound statement, which is simply a number of simple or compound ones enclosed in {}.  There is no semicolon after ‘}’ of a compound statement, however there is a semicolon after the last non-compound statement within the {}. 

While Statement; Assignment within an Expression; Null Statement:

The fundamental looping method in C is the while statement. Here is a program which copies its input to its output a character at a time. Keep in mind that `\0' marks the end of file.

main( ) {
               char c;
               while( (c=getchar( )) != '\0' )                           
               putchar(c);
       }

While statement is a loop, whose common form is
while (expression) statement

Its meaning is:

(i) Compute the expression
(ii) If its value is true (that is, not zero) do the statement, and go back to (i)

Since the expression is tested prior to the statement is executed, the statement portion can be executed zero times, that is frequently desirable. As in if statement, the expression and the statement can both be arbitrarily complex, though we haven't seen that yet. Our instance gets the character, assigns it to c, and then tests if it is a `\0''. If it is not a `\0', the statement portion of the while is executed, and prints the character. The while then repeats.

Whenever the input character is finally a `\0', the while finishes, and therefore does main.

Notice that we employed an assignment statement 
  

c = getchar( )

in an expression. This is a handy notational shortcut that frequently generates clearer code. (However it is often the only method to write the code cleanly. As an exercise, rewrite the file-copy devoid of employing an assignment within an expression). It works since an assignment statement has a value, merely as any other expression does. Its value is the value of right hand side. This as well implies that we can employ multiple assignments such as

x = y = z = 0;

Computation goes from right to left.

The extra parentheses in the assignment statement in the conditional were really essential: if we had state:

c = getchar( ) != '\0'

Here c would be set to 0 or 1 based on whether the character fetched was an end of the file or not. This is since in the absence of parentheses the assignment operator `=' is computed after the relational operator `!='.  Whenever in doubt, or even if not, parenthesize.

main( ) {
           while( putchar(getchar( )) != '\0' ) ;   }


Else Clause; Conditional Expressions:

We just employed an else after an ‘if’. The most common form of ‘if’ is

if (expression) statement1 else statement2

the else portion is optional, however often helpful. The canonical illustration sets x to the minimum of a and b:

if (a < b)
               x = a;
       else
               x = b;

C gives an alternate form of conditional which is frequently more concise. It is termed as the ‘conditional expression' since it is a conditional that really has a value and can be employed anywhere an expression can. The value of

a<b ? a : b;

is a if a is less than b; it is b or else. In common, the form

expr1 ? expr2 : expr3

To set x to minimum of a and b, then:

x = (a<b ? a : b);

The parentheses are not essential since `?:' is computed before `=', however safety first.  Going a step further, we could write the loop in lower-case program as:

while( (c=getchar( )) != '\0' )
putchar( ('A'<=c && c<='Z') ? c-'A'+'a' : c );

If's and else's can be employed to construct logic which branches one of some ways and then rejoins, a common programming structure, in this manner:

       if(...)
               {...}
       else if(...)
               {...}
       else if(...)
               {...}  else  {...}

Conditions are tested in order, and precisely one block is executed; either the first one whose if is pleased, or the one for the last else. Whenever this block is completed, the next statement executed is the one subsequent to the last else. When no action is to be taken for the ‘default’ case, omit the last else.

For illustration, to count letters, digits and others in a file, we could write:

  main( ) {
          int let, dig, other, c;
          let = dig = other = 0;
          while( (c=getchar( )) != '\0' )
                  if( ('A'<=c && c<='Z') || ('a'<=c &&  c<='z') )
                        ++let;
                  else if( '0'<=c && c<='9' ) ++dig;
                  else  ++other;
          printf("%d letters, %d digits, %d others\n", let, dig, other);
  }

This digits, code letters and others in a file.

Latest technology based Programming Languages Online Tutoring Assistance

Tutors, at the www.tutorsglobe.com, take pledge to provide full satisfaction and assurance in Programming Languages help via online tutoring. Students are getting 100% satisfaction by online tutors across the globe. Here you can get homework help for Programming Languages, project ideas and tutorials. We provide email based Programming Languages help. You can join us to ask queries 24x7 with live, experienced and qualified online tutors specialized in Programming Languages. Through Online Tutoring, you would be able to complete your homework or assignments at your home. Tutors at the TutorsGlobe are committed to provide the best quality online tutoring assistance for Programming Languages Homework help and assignment help services. They use their experience, as they have solved thousands of the Programming Languages assignments, which may help you to solve your complex issues of Programming Languages. TutorsGlobe assure for the best quality compliance to your homework. Compromise with quality is not in our dictionary. If we feel that we are not able to provide the homework help as per the deadline or given instruction by the student, we refund the money of the student without any delay.

©TutorsGlobe All rights reserved 2022-2023.