C Tutorial: Language
1. First program
The C program is a set of functions.
The program execution begins by executing the function main ().
#include <stdio.h>
main(){
printf("Hi \n");
}
2. C Language Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
3. main() function
In all C programs, the starting point is the main() function.
Every C program has one.
#include <stdio.h>
int main()
{
printf("Goodbye!\n");
return 0;
}
4. Command Line Arguments
List the command line arguments
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Program name: %s\n", argv[0]);
int i;
for (i = 1; i < argc; i++)
printf("\nArgument %d: %s", i, argv[i]);
return 0;
}
5. Variable Declaration
5.1. Variables
You can store values in variables.
Each variable is identified by a variable name.
Each variable has a variable type.
Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores.
Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables.
The variables are defined at the begining of the block.The following is an example of some variable names:
average /* average of all grades */
pi /* pi to 6 decimal places */
number_of_students /* number students in this class */
The following are not variable names:
3rd_ /* Begins with a number */
all$ /* Contains a "$" */
the end /* Contains a space */
int /* Reserved word */
Meaningful variable name:
entry_total /* total number of items in current entry */
all_total /* total of all entries */
5.2. How to declare a variable
A variable declaration serves three purposes:
- It defines the name of the variable.
- It defines the type of the variable (integer, real, character, etc.).
- It gives the programmer a description of the variable.
int answer; /* the result of our expression */
The keyword int tells C that this variable contains an integer value.
The variable name is answer.
The semicolon (;) marks the end of the statement.
The comment is used to define this variable for the programmer. 5.3. Using a variable to store value
#include <stdio.h>
int main(void)
{
int salary;
salary = 10000;
printf("My salary is %d.\n", salary);
return 0;
}
5.4. Initize int value in declaration
#include <stdio.h>
int main(void)
{
int number0 = 10, number1 = 40, number2 = 50, number3 = 80, number4 = 10;
int number5 = 20, number6 = 30, number7 = 60, number8 = 70, number9 = 110;
int sum = number0 + number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8 + number9;
float average = (float)sum / 10.0f;
printf("\nAverage of the ten numbers entered is : %f\n", average);
return 0;
}
5.5. Meaningful variable name
int p, q, r;
Now consider another declaration:
int account_number;
int balance_owed;
int account_number; /* Index for account table */
int balance_owed; /* Total owed us (in pennies)*/
5.6. Define three variables and use assignment operator to assign
int main()
{
int term; /* term used in two expressions */
int term_2; /* twice term */
int term_3; /* three time term */
term = 3 * 5;
term_2 = 2 * term;
term_3 = 3 * term;
return 0;
}
5.7. Use printf to output variable
#include <stdio.h>
int main()
{
int term; /* term used in two expressions */
term = 3 * 5;
printf("Twice %d is %d\n", term, 2 * term);
printf("Three times %d is %d\n", term, 3 * term);
return 0;
}
The number of %d conversions should match the number of expressions.
6. Variable Output
6.1. Printing Variable Contents
Use the printf function with formatting options.
#include <stdio.h>
main()
{
int x;
float y;
char c;
x = -4443;
y = 554.21;
c = 'M';
printf("\nThe value of integer variable x is %d", x);
printf("\nThe value of float variable y is %f", y);
printf("\nThe value of character c is %c\n", c);
}
Conversion specifiers are made up of two characters: % and a special character.
The special character tells the program how to convert the data.
Conversion Specifier | Description |
%d | Displays integer value |
%f | Displays floating-point numbers |
%c | Displays character |
7. Variable Size and Limitation
7.1. Finding the limits
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(void)
{
printf("Variables of type char store values from %d to %d", CHAR_MIN, CHAR_MAX);
printf("\nVariables of type unsigned char store values from 0 to %u", UCHAR_MAX);
printf("\nVariables of type short store values from %d to %d", SHRT_MIN, SHRT_MAX);
printf("\nVariables of type unsigned short store values from 0 to %u",USHRT_MAX);
printf("\nVariables of type int store values from %d to %d", INT_MIN, INT_MAX);
printf("\nVariables of type unsigned int store values from 0 to %u", UINT_MAX);
printf("\nVariables of type long store values from %ld to %ld", LONG_MIN, LONG_MAX);
printf("\nVariables of type unsigned long store values from 0 to %lu", ULONG_MAX);
printf("\nVariables of type long long store values from %lld to %lld", LLONG_MIN, LLONG_MAX);
printf("\nVariables of type unsigned long long store values from 0 to %llu", ULLONG_MAX);
printf("\n\nThe size of the smallest non-zero value of type float is %.3e", FLT_MIN);
printf("\nThe size of the largest value of type float is %.3e", FLT_MAX);
printf("\nThe size of the smallest non-zero value of type double is %.3e", DBL_MIN);
printf("\nThe size of the largest value of type double is %.3e", DBL_MAX);
printf("\nThe size of the smallest non-zero value of type long double is %.3Le", LDBL_MIN);
printf("\nThe size of the largest value of type long double is %.3Le\n", LDBL_MAX);
printf("\nVariables of type float provide %u decimal digits precision.", FLT_DIG);
printf("\nVariables of type double provide %u decimal digits precision.", DBL_DIG);
printf("\nVariables of type long double provide %u decimal digits precision.", LDBL_DIG);
return 0;
}
7.2. Finding the size of a type
#include <stdio.h>
int main(void)
{
printf("\nVariables of type char occupy %d bytes", sizeof(char));
printf("\nVariables of type short occupy %d bytes", sizeof(short));
printf("\nVariables of type int occupy %d bytes", sizeof(int));
printf("\nVariables of type long occupy %d bytes", sizeof(long));
printf("\nVariables of type float occupy %d bytes", sizeof(float));
printf("\nVariables of type double occupy %d bytes", sizeof(double));
printf("\nVariables of type long double occupy %d bytes", sizeof(long double));
return 0;
}
8. Variable Scope
8.1. Scope of variables
Variable can be defined in the block.
The blocks are marked using { and } braces.
The scope of the variable is in the block where it is declared.
Variable defined in the outer block can be used in the inner block.
The nearest definition has more precedence.
#include <stdio.h>
main()
{
int i = 10;
{
int i = 0;
for (i = 0; i < 2; i++)
{
printf("value of i is %d\n", i);
}
}
printf("the value of i is %d\n", i);
}
8.2. Inner variable shadows outer variable
#include <stdio.h>
int main(void)
{
int count = 0;
do {
int count = 0;
++count;
printf("\ncount = %d ", count);
} while(++count <= 8); /* This works with outer count */
/* this is outer */
printf("\ncount = %d\n", count);
return 0;
}
9. Global variables
9.1. Declare global variables
A global variable is available to all functions in your program.
A local variable is available only to the function in which it's created.
- Global variables are declared outside of any function.
- Global variables are typically declared right before the main() function.
- You can also declare a group of global variables at one time:
int s,t;
And, you can preassign values to global variables, if you want:
char prompt[]="What?";
9.2. Define and use Gloabal variables
#include <stdio.h>
int count = 0; /* Declare a global variable */
void test1(void)
{
printf("\ntest1 count = %d ", ++count);
}
void test2(void)
{
static int count; /* This hides the global count */
printf("\ntest2 count = %d", ++count);
}
int main(void)
{
int count = 0; /* This hides the global count */
for (; count < 5; count++)
{
test1();
test2();
}
return 0;
}
10. Local variable
10.1. Local variable shadows global variable
#include <stdio.h>
int i = 0; // Global variable
main()
{
int i; // local variable
i = 0;
printf("value of i in main %d\n", i);
f1();
printf("value of i after call %d\n", i);
}
f1(void)
{
int i = 0;
i = 50;
}
11. static Variables
11.1. Static variable
#include <stdio.h>
int g = 10;
main()
{
int i = 0;
void f1();
f1();
printf("after first call \n");
f1();
printf("after second call \n");
f1();
printf("after third call \n");
}
void f1()
{
static int k = 0;
int j = 10;
printf("value of k %d j %d\n", k, j);
k = k + 10;
}
11.2. static Versus automatic Variable
#include <stdio.h>
void test1(void)
{
int count = 0;
printf("\ntest1 count = %d ", ++count);
}
void test2(void)
{
static int count = 0;
printf("\ntest2 count = %d ", ++count);
}
int main(void)
{
int i;
for(i = 0; i < 5; i++)
{
test1();
test2();
}
return 0;
}
12. Variable Address
12.1. Output address and value
#include <stdio.h>
int main(void)
{
int number = 0;
int *pointer = NULL;
number = 10;
printf("\nnumber's address: %p", &number);
printf("\nnumber's value: %d\n\n", number);
return 0;
}
12.2. Using the & operator
#include <stdio.h>
int main(void)
{
long a = 1L;
long b = 2L;
long c = 3L;
double d = 4.0;
double e = 5.0;
double f = 6.0;
printf("A variable of type long occupies %d bytes.", sizeof(long));
printf("\nHere are the addresses of some variables of type long:");
printf("\nThe address of a is: %p The address of b is: %p", &a, &b);
printf("\nThe address of c is: %p", &c);
printf("\n\nA variable of type double occupies %d bytes.", sizeof(double));
printf("\nHere are the addresses of some variable of type double:");
printf("\nThe address of d is: %p The address of e is: %p", &d, &e);
printf("\nThe address of f is: %p\n", &f);
return 0;
}
13. Variable Pointer
13.1. Output value at the address
#include <stdio.h>
int main(void)
{
int number = 0;
int *pointer = NULL;
number = 10;
pointer = &number;
printf("\npointer's value: %p", pointer);/* Output the value (an address) */
printf("\nvalue pointed to: %d\n", *pointer); /* Value at the address */
return 0;
}
13.2. Put values in the memory locations by using pointers
#include <stdio.h>
main()
{
int a[5];
int *b;
int *c;
int i;
for (i = 0; i < 5; i++)
{
a[i] = i;
}
for (i = 0; i < 5; i++)
{
printf("value in array %d\n", a[i]);
}
b = a;
*b = 4;
b++;
*b = 6;
b++;
*b = 8;
b++;
*b = 10;
b++;
*b = 12;
printf("after\n\n\n");
for(i = 0; i < 5; i++)
{
printf("value in array %d\n", a[i]);
}
}
14. Variable argument lists
14.1. Calculate an average using variable argument lists
#include <stdio.h>
#include <stdarg.h>
double average(double v1, double v2, ...); /* Function prototype */
int main(void)
{
double value1 = 10.5, value2 = 2.5;
int number1 = 6, number2 = 5;
long number3 = 12, number4 = 20;
printf("\n Average = %lf", average(value1, 3.5, value2, 4.5, 0.0));
printf("\n Average = %lf", average(1.0, 2.0, 0.0));
printf("\n Average = %lf", average((double)number2, value2, (double)number1, (double)number4, (double)number3, 0.0));
return 0;
}
/* Function to calculate the average of a variable number of arguments */
double average(double v1, double v2, ...)
{
va_list parg; /* Pointer for variable argument list */
double sum = v1 + v2; /* Accumulate sum of the arguments */
double value = 0; /* Argument value */
int count = 2; /* Count of number of arguments */
va_start(parg, v2); /* Initialize argument pointer */
while ((value = va_arg(parg, double)) != 0.0)
{
sum += value;
count++;
}
va_end(parg); /* End variable argument process */
return sum/count;
}
15. Comments
15.1. Adding Comments
Comments in a C program have a starting point and an ending point.
Everything between those two points is ignored by the compiler.
/* This is how a comment looks in the C language */
The beginning of the comment is marked by the slash and the asterisk: /*.
The end of the comment is marked by the asterisk and the slash: */.
#include <stdio.h>
int main()
{
/* This is the comment. */
printf("%15s", "right\n");
printf("%-15s", "left\n");
return 0;
}
15.2. Using Comments to Disable
Comments are ignored by the compiler. You can use comments to disable certain parts of your program.
#include <stdio.h>
int main()
{
/* printf("%15s", "right\n"); */
printf("%-15s", "left\n");
return 0;
}
15.3. The comments are enclosed in '/*...*/'
#include <stdio.h>
main()
{
printf("Hi \n"); /* This is the comments */
}
15.4. The '//' is used as single line comment
#include <stdio.h>
main()
{
int i, j, k;
i = 6;
j = 8;
k = i + j;
printf("sum of two numbers is %d \n", k); // end of line comment
}
15.5. Source code header comments
At the beginning of the program is a comment block.
The comment block contains information about the program.
Boxing the comments makes them stand out.
The some of the sections as follows should be included.
- Heading.
- Author.
- Purpose.
- Usage.
- References.
- File formats. A short description of the formats which will be used in the program.
- Restrictions.
- Revision history.
- Error handling.
- Notes. Include special comments or other information that has not already been covered.
/************************************************
* hello -- program to print out "Hello World". *
* *
* Author: FirstName, LastName *
* *
* Purpose: Demostration of a simple program. *
* *
* Usage: *
* Run the program and the message appears. *
************************************************/
#include <stdio.h>
int main()
{
/* The the world hello */
printf("Hello World\n");
return 0;
}
16. Convention
16.1. Indentation and Code Format
while (! done) {
printf("Processing\n");
next_entry();
}
if (total <= 0) {
printf("You owe nothing\n");
total = 0;
} else {
printf("You owe %d dollars\n", total);
all_totals = all_totals + total;
}
In this case, curly braces ({}) are put on the same line as the statements.
The other style puts the {} on lines by themselves:
while (! done)
{
printf("Processing\n");
next_entry();
}
if (total <= 0)
{
printf("You owe nothing\n");
total = 0;
}
else
{
printf("You owe %d dollars\n", total);
all_totals = all_totals + total;
}
16.2. Clarity
/* poor programming practice */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;
temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;
A better version would be:
/*
* Swap the two corners
*/
/* Swap X coordinate */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;
/* Swap Y coordinate */
temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;
17. Header Files
17.1. Include header file
#include <stdio.h>
int main(void)
{
printf("\nBe careful!!\a");
return 0;
}
17.2. Include the header file for input and output
#include <stdio.h>
int main(void)
{
printf("A\n\n\nB");
printf("\t1.\tA \n");
printf("\t2.\tA \n");
printf("\t3.\tA \n");
printf("\n\t\t\b\bA\n\n");
return 0;
}
17.3. Headers
Each function in the C standard library has its associated header.
The headers are included using #include.
Header Including obtains the Declarations for the standard library functions.17.4. Common Headers
Header | Purpose |
assert.h | Defines the assert() macro |
ctype.h | Character handling |
errno.h | Error reporting |
float.h | Defines implementation-dependent floating-point limits |
limits.h | dependent limits |
locale.h | Localization |
math.h | math library |
setjmp.h | Nonlocal jumps |
signal.h | Signal handling |
stdarg.h | Variable argument lists |
stddef.h | Constants |
stdio.h | I/O system |
stdlib.h | Miscellaneous declarations |
string.h | string functions |
time.h | system time functions |
17.5. Headers Added by C99
Header | Purpose |
complex.h | complex arithmetic |
fenv.h | Gives access to the floating-point status flags and other aspects of the floating-point environment |
inttypes.h | Defines a standard, portable set of integer type names. Also supports functions that handle greatest-width integers |
iso646.h | Added in 1995 by Amendment. Defines macros that correspond to various operators, such as && and ^ |
stdbool.h | Supports Boolean data types. Defines the macro bool, which helps with C++ compatibility |
stdint.h | Defines a standard, portable set of integer type names |
tgmath.h | Defines type-generic floating-point macros |
wchar.h | multibyte and wide-character functions |
wctype.h | multibyte and wide-character classification functions |
17.6. Macros in Headers
Define the macro name using #define:
#define abs
Undefine the macro name using #undef.
#undef abs
18. External references
18.1. External references
Extern definition is used when referencing a function or variable defined outside.
// Program in file external1.c
#include <stdio.h>
extern int i;
main()
{
i = 0;
printf("value of i %d\n", i);
}
Another file:
// Program in file f1.c
int i = 7;
19. gcc
19.1. Compile and link the C program using gcc
Compile and link the goodbye.c source code:
$ gcc goodbye.c -o test
Original file:
#include <stdio.h>
int main()
{
printf("Goodbye!\n");
return 0;
}