Ticker

6/recent/ticker-posts

Basic C Syntax

Chapter 3: Basic C Syntax

 


3.1 Structure of a C Program:

A C program consists of a collection of functions,
where the execution starts from the main() function. The general structure of a
C program is as follows:

 



#include <stdio.h> // Include
necessary header files



 



// Function prototype (if required)



 



int main() {



   
// Code goes here



   



   
return 0; // Indicate successful program execution



}



 

 

§  `#include
<stdio.h>`: This line includes the standard input/output library, which
provides functions like `printf()` and `scanf()`. Other libraries can be
included as per the program's requirements.

 

§  `int
main()`: This is the main function that serves as the entry point of a C
program. It returns an integer value (0 in this case) to indicate successful
program execution. The `main()` function contains the program's logic and is
enclosed within curly braces `{}`.

 

3.2 Comments:

Comments are used to add explanatory notes to the
code, which are ignored by the compiler. They can improve code readability and
serve as documentation for other developers. There are two types of comments in
C:

 

- Single-line comments: These comments start with
`//` and continue until the end of the line.

 



// This is a
single-line comment



 

 

·        
Multi-line comments: These comments
start with `/*` and end with `*/`, allowing comments to span multiple lines.

·        
 



/* This is a



   multi-line comment */



 

 

3.3 Writing and Executing Your First C Program:

 

Let's write a simple program that displays
"Hello, World!" on the console:

 



#include
<stdio.h>



int main() {



    printf("Hello, World!\n");



    return 0;



}



 

 

§  `#include
<stdio.h>`: We include the stdio.h header file to use the `printf()`
function.

 

§  `printf("Hello,
World!\n");`: The `printf()` function is used to print the specified text
on the console. `\n` represents a new line character.

 

§  `return
0;`: The `return` statement exits the `main()` function and returns 0 to the
operating system, indicating successful program execution.

 

To
compile and execute the program:

 

1. Save the code in a file with a ".c"
extension (e.g., "hello.c").

2. Open the terminal or command prompt and navigate
to the directory containing the C file.

3. Compile the program using the command: `gcc
hello.c -o hello`.

·        
This command uses the GCC compiler
(`gcc`) to compile the "hello.c" file and produce an executable named
"hello" (specified with `-o`).

4. Once the compilation is successful, execute the
program using the command: `./hello`.

·        
This command runs the generated
executable, resulting in the output: "Hello, World!".

 



































































































 

Post a Comment

0 Comments