mirror of
https://github.com/janishutz/eth-summaries.git
synced 2026-01-12 14:18:23 +00:00
[SPCA] Start C syntax summary
This commit is contained in:
16
semester3/spca/code-examples/00_c/01_syntax/00_intro.c
Normal file
16
semester3/spca/code-examples/00_c/01_syntax/00_intro.c
Normal file
@@ -0,0 +1,16 @@
|
||||
// This is a line comment
|
||||
/* this is a block comment */
|
||||
#include "01_func.h" // Relative import
|
||||
|
||||
int i = 0; // This allocates an integer on the stack
|
||||
|
||||
int main( int argc, char *argv[] ) {
|
||||
// This is the function body of a function (here the main function)
|
||||
// which serves as the entrypoint to the program in C and has arguments
|
||||
printf( "Argc: %d\n", argc ); // Number of arguments passed, always >= 1
|
||||
// (first argument is the executable name)
|
||||
for ( int i = 0; i < argc; i++ ) // For loop just like any other sane programming language
|
||||
printf( "Arg %d: %s\n", i, argv[ i ] ); // Outputs the i-th argument from CLI
|
||||
|
||||
get_user_input_int( "Select a number" );
|
||||
}
|
||||
37
semester3/spca/code-examples/00_c/01_syntax/01_func.c
Normal file
37
semester3/spca/code-examples/00_c/01_syntax/01_func.c
Normal file
@@ -0,0 +1,37 @@
|
||||
#include "01_func.h"
|
||||
|
||||
int get_user_input_int( char prompt[] ) {
|
||||
int input_data;
|
||||
printf( "%s", prompt ); // Always wrap strings like this for printf
|
||||
scanf( "%d", &input_data ); // Get user input from CLI
|
||||
|
||||
// If statements just like any other language
|
||||
if ( input_data )
|
||||
printf( "Not 0" );
|
||||
else
|
||||
printf( "Input is zero" );
|
||||
|
||||
switch ( input_data ) {
|
||||
case 5:
|
||||
printf( "You win!" );
|
||||
break; // Doesn't fall through
|
||||
case 6:
|
||||
printf( "You were close" ); // Falls through
|
||||
default:
|
||||
printf( "No win" ); // Case for any not covered input
|
||||
}
|
||||
|
||||
int input_data_copy = input_data;
|
||||
|
||||
while ( input_data > 1 ) {
|
||||
input_data -= 1;
|
||||
printf( "Hello World" );
|
||||
}
|
||||
|
||||
do {
|
||||
input_data -= 1;
|
||||
printf( "Bye World" );
|
||||
} while ( input_data_copy > 1 );
|
||||
|
||||
return 0;
|
||||
}
|
||||
4
semester3/spca/code-examples/00_c/01_syntax/01_func.h
Normal file
4
semester3/spca/code-examples/00_c/01_syntax/01_func.h
Normal file
@@ -0,0 +1,4 @@
|
||||
#include <stdio.h> // Import from system path
|
||||
// (like library imports in other languages)
|
||||
|
||||
int get_user_input_int( char prompt[] );
|
||||
Reference in New Issue
Block a user